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;
    }

}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值