spring boot 1.5配置全局异常处理

2017-12-08  本文已影响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;

}

上一篇下一篇

猜你喜欢

热点阅读