您的位置:首页 > 编程语言 > Java开发

springMVC异常统一处理

2017-09-11 10:25 411 查看
先以统一处理validation抛出的异常为例。

// 该注解在4.0后支持对指定包、类进行管理annotations(), basePackageClasses(), basePackages()
@ControllerAdvice
public class ValidateControllerAdvice {

/**
* bean入参校验未通过异常捕获
*/
@ExceptionHandler(MethodArgumentNotValidException.class)//ExceptionHandler来表示需要捕获的异常类型
public String validExceptionHandler(MethodArgumentNotValidException e, HttpServletRequest request,
HttpServletResponse response) {

// 判断是ajax请求还是页面类型请求
if (AjaxUtils.isAjaxRequest(request)) {
CommonResponse commonResponse = new CommonResponse();
commonResponse.setCode(ErrorObjects.E1001.getErrorCode());
commonResponse.setDesc(e.getBindingResult().getFieldError().getDefaultMessage());

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(new Gson().toJson(commonResponse));
} catch (IOException e1) {
commonResponse.setCode(ErrorObjects.E9999.getErrorCode());
commonResponse.setDesc(ErrorObjects.E9999.getErrorDetail());
e1.printStackTrace();
}
return null;
} else {
// 跳转到异常页面(携带异常原因)
request.setAttribute("code", ErrorObjects.E1001.getErrorCode());
request.setAttribute("desc", e.getBindingResult().getFieldError().getDefaultMessage());
return "Error";
}

}

}


因为http请求有时候是AJAX请求、有时是请求页面,所以要对请求进行判断,如果是页面请求,则跳转统一的错误页面

public class AjaxUtils {

/**
* 验证是否是ajax请求
*/
public static boolean isAjaxRequest(HttpServletRequest servletRequest) {

String requestedWith = servletRequest.getHeader("X-Requested-With");

if (StringUtils.isBlank(requestedWith)) {
requestedWith = servletRequest.getHeader("x-requested-with");
}

return requestedWith != null ? "XMLHttpRequest".equalsIgnoreCase(requestedWith) : false;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: