@controllerAdvice 统一处理异常

spring3.2版本提供了新注解@controllerAdvice,意为控制器增强。配合@ExceptionHandler注解可以统一处理异常

注:需开启<mvc:annotation-drive>

 

@ControllerAdvice
public class DefaultExceptionHandler {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 统一异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    @ResponseBody
    public HttpResponseEntity exceptionResolver(Throwable e) {
        if (e instanceof UnauthorizedException) {
            logger.warn("用户权限不足", e);
            return new HttpResponseEntity(HttpStatus.FORBIDDEN);
        } else if (e instanceof WechatAuthcException) {
            return wechatAuthcExceptionHandle((WechatAuthcException) e);
        } else if (e instanceof BindException) {
            BindingResult bindingResult = ((BindException) e).getBindingResult();
            return requestParamsExceptionHandle(bindingResult);
        } else if (e instanceof MaxUploadSizeExceededException) {
            return new HttpResponseEntity(HttpStatus.ERROR_PARAMS_REQUEST, "文件只支持10MB以下");
        } else if (e instanceof StBusinessException) {
            StBusinessException exception = (StBusinessException) e;
            if (!ErrorDefintions.DEFAULT_FAULT_TYPE.equals(exception.getErrorType())) {
                // 错误日志
                logger.error("业务异常", e);
            }
            return new HttpResponseEntity(exception.getErrorCode(), exception.getMessageWithoutCode());
        }
        logger.error("统一异常处理", e);
        return new HttpResponseEntity().failed();
    }

    /**
     * 参数规则验证
     *
     * @param bindingResult
     * @return
     */
    public HttpResponseEntity requestParamsExceptionHandle(BindingResult bindingResult) {
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        Map<String, String> errorMsg = new HashMap<>();
        for (FieldError fieldError : fieldErrors) {
            errorMsg.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return new HttpResponseEntity(HttpStatus.ERROR_PARAMS_REQUEST, errorMsg);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值