全局拦截处理ControllerAdvice

统一异常拦截类

​
@ControllerAdvice
public class GlobalExceptionHandler {
    public static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = ServiceException.class)
    @ResponseBody
    public ResponseResult<String> serviceExceptionHandler(ServiceException e) {
        logger.warn("发生业务错误,原因:{}", e.getMessage());
        return ResponseResult.customResult(e.getExceptionEnum());
    }

    
    @ExceptionHandler(value = UnauthorizedException.class)
    @ResponseBody
    public ResponseResult<String> unauthorizedExceptionHandler(UnauthorizedException e) {
        logger.warn("接口请求权限错误:{}", e.getMessage());
        return ResponseResult.customResult(CommonExceptionEnum.NO_PERMISSION);
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseResult<String> exceptionHandler(Exception e) {
        e.printStackTrace();
        logger.warn("未知错误,原因:{}", e.getMessage());
        return ResponseResult.customResult(CommonExceptionEnum.DEFAULT_ERROR);
    }

    /**
     * 参数异常统一处理
     */
    @Order(1)
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult<Object> validationException(MethodArgumentNotValidException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        FieldError fieldError;
        if (bindingResult.hasErrors() && (fieldError = bindingResult.getFieldError()) != null) {
            return ResponseResult.customResult(CommonExceptionEnum.PARAM_ERROR, fieldError.getDefaultMessage());
        } else {
            return ResponseResult.customResult(CommonExceptionEnum.DEFAULT_ERROR);
        }
    }
}

​

统一请求参数校验类

/**
     * 参数异常统一处理
     */
    @Order(1)
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult<Object> validationException(MethodArgumentNotValidException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        FieldError fieldError;
        if (bindingResult.hasErrors() && (fieldError = bindingResult.getFieldError()) != null) {
            return ResponseResult.customResult(CommonExceptionEnum.PARAM_ERROR, fieldError.getDefaultMessage());
        } else {
            return ResponseResult.customResult(CommonExceptionEnum.DEFAULT_ERROR);
        }
    }
    @PostMapping(value = "/123")
    public ResponseResult<String> saveOrg(@RequestBody @Valid SaveOrgDto sysZcjg) {
        return sysZcjgService.saveOrg(sysZcjg);
    }
public class SaveOrgDto {
    @NotBlank(message = "xxx不能为空")
    private String jgbm;
}

https://zhuanlan.zhihu.com/p/158774914

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值