在接口访问的过程中,经常会遇到错误信息响应的问题,常见的错误信息大致可分为两种情况
1、系统运行时的未知异常,直接将这种异常返回给客户端是不怎么友好的。
2、根据业务需求和程序设计,需要主动返回给客户端的异常或错误信息,这种情况会增加很多重复工作量。
springboot中使用@RestControllerAdvice和@ExceptionHandler注解的结合使用,能够很好解决上面的问题。
@RestControllerAdvice:使用再类上面,会将其使用了@ExceptionHandler的成员方法作用的到所有使用了@RequestMapping的方法上。
@ExceptionHandler:接收其作用方法中抛出的指定异常,并将处理结果返回给客户端。若配置了多个@ExceptionHandler,当程序抛出异常时,根据异常类型,按继承关系,匹配与之类型最接近的@ExceptionHandler处理。
统一异常处理类配置
/**
* @description: controller全局配置<br>
* @version: 1.0 <br>
* @since jdk11.0.5_10
*/
@Slf4j
@RestControllerAdvice
public class AdviceController {
private final String API_ERROR = "API访问异常";
/**
* @description: RuntimeException统一处理方法<br>
* @version: 1.0 <br>
* @param: e
* @return org.springframework.http.ResponseEntity<?>
*/
@ExceptionHandler({RuntimeException.class})
public ResponseEntity<String> runtimeExceptionHandler(RuntimeException e){
log.error(API_ERROR,e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("系统错误,请联系维护人员");
}
/**
* @description: 主动抛出的异常处理 <br>
* @version: 1.0 <br>
* @param: e
* @return org.springframework.http.ResponseEntity<java.lang.String>
*/
@ExceptionHandler({VoluntaryException.class})
public ResponseEntity<String> voluntaryExceptionHandler(VoluntaryException e){
if(ObjectUtils.isEmpty(e)){
log.error(API_ERROR);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
log.error(API_ERROR,e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
自定义异常类
public class VoluntaryException extends RuntimeException{
private static final long serialVersionUID = 5044938065901970022L;
public VoluntaryException() {
}
public VoluntaryException(String message) {
super(message);
}
public VoluntaryException(String message, Throwable cause) {
super(message, cause);
}
}
测试方法
@GetMapping("/test4")
public void test4(){
throw new RuntimeException("未知的错误");
//返回“系统错误,请联系维护人员”
}
@GetMapping("/test5")
public void test5(){
throw new VoluntaryException("主动抛出的异常");
//返回“主动抛出的异常”
}