springMVC异常统一处理

先以统一处理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;
    }

}

猜你喜欢

转载自blog.csdn.net/qq_33144861/article/details/77930388