美文网首页
spring boot 1.5配置全局异常处理

spring boot 1.5配置全局异常处理

作者: 邓锟 | 来源:发表于2017-12-08 16:45 被阅读0次

    网上的资料大多代码不全或者功能不全,自己写了一份可用的供参考。

    解决的问题:

    根据方法名结尾来确认返回html页面或者json格式

    /**

    * Ajax结尾的,统一返回json异常格式

    * @param request

    * @return

    */

    private Boolean isAjax(HttpServletRequest request){

    String requestURI = request.getRequestURI();

    return StringUtils.endsWithIgnoreCase(requestURI, "Ajax");

    }

    @ExceptionHandler(value = Exception.class)

    public Object defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {

    logger.error("uri:" + request.getRequestURI() +  " error:" + e.getMessage());

    if(isAjax(request)) {

    ResponseDto resp = new ResponseDto(CommonResponseEnum.SYSTEM_ERROR);

    resp.setData(e.getMessage());

    return render(resp,response);

    } else {

    ModelAndView mav = new ModelAndView();

    mav.addObject("exception", e);

    mav.addObject("url", request.getRequestURL());

    mav.setViewName(DEFAULT_ERROR_VIEW);

    return mav;

    }

    }

    /**

    * 转换成response方式返回

    * @param model

    * @param response

    * @return

    */

    public static ModelAndView render(Object model, HttpServletResponse response)

    {

    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();

    MediaType jsonMimeType = MediaType.APPLICATION_JSON;

    try {

    jsonConverter.write(model, jsonMimeType, new ServletServerHttpResponse(response));

    } catch (HttpMessageNotWritableException e) {

    e.printStackTrace();

    } catch (IOException e) {

    e.printStackTrace();

    }

    return null;

    }

    相关文章

      网友评论

          本文标题:spring boot 1.5配置全局异常处理

          本文链接:https://www.haomeiwen.com/subject/sboeixtx.html