Spring Boot @ControllerAdvice+@ExceptionHandler处理controller异常

需求:

  1.spring boot 项目restful 风格统一放回json

  2.不在controller写try catch代码块简洁controller层

  3.对异常做统一处理,同时处理@Validated 校验器注解的异常

方法:

  @ControllerAdvice 注解定义全局异常处理类

  

@ControllerAdvice
public class ControllerExceptionHandler {

}

  @ExceptionHandler 注解声明异常处理方法

@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ResponseResult handlerException(Exception e){
logger.error(e.getMessage(),e);
ResponseResult responseResult = new ResponseResult(ResponseCode.ERROR,e.getMessage());
return responseResult;
}

  处理@Validated 校验器注解的异常

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ResponseResult handlerMethodArgumentException(MethodArgumentNotValidException e){
logger.error(e.getMessage(),e);

BindingResult bindingResult = e.getBindingResult();
String message = ValidMethodUtils.validMethod(bindingResult);
ResponseResult responseResult = new ResponseResult(ResponseCode.ERROR,message);
return responseResult;
}

完整代码如下:

package com.travelsky.travelcloud.exception;

import com.travelsky.travelcloud.utils.ResponseCode;
import com.travelsky.travelcloud.utils.ResponseResult;
import com.travelsky.travelcloud.utils.bizutils.ValidMethodUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**异常统一处理的类
* Created by Liyan on 2018/3/22.
*/
@ControllerAdvice
public class ControllerExceptionHandler {

private static final Logger logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);

/*create by LiYan on 2018.3.25.
* 处理不可预知的异常
* */
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ResponseResult handlerException(Exception e){
logger.error(e.getMessage(),e);
ResponseResult responseResult = new ResponseResult(ResponseCode.ERROR,e.getMessage());
return responseResult;
}

/*create by LiYan on 2018.3.30.
* 处理接口数据校验的异常
* */
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ResponseResult handlerMethodArgumentException(MethodArgumentNotValidException e){
logger.error(e.getMessage(),e);

BindingResult bindingResult = e.getBindingResult();
String message = ValidMethodUtils.validMethod(bindingResult);
ResponseResult responseResult = new ResponseResult(ResponseCode.ERROR,message);
return responseResult;
}

}

如处理自定义异常可修改如下注解

@ExceptionHandler(自定义异常.class)

原文地址:https://www.cnblogs.com/HanShisi/p/8717065.html