背景
在项目开发中,除了bug就是各种异常,那么异常怎么处理呢。比如,在业务处理中,对整个项目要做统一的返回值处理,那出了异常怎么办。直接来个500,400?
全局异常捕获,可以捕获自定义的异常,在业务开发中,直接随手抛异常。全局控制返回值
1、自定义异常
先定义自定义异常,下一步全局捕获时要用到
import lombok.Data;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode(callSuper = true)
@Data
public class ApiRequestErrorException extends RuntimeException{
private int errorCode;
public ApiRequestErrorException(String msg){
super(msg);
}
public ApiRequestErrorException(String msg, int errorCode){
super(msg);
this.errorCode = errorCode;
}
}
2、捕获异常
这里的枚举类ResponseError.REQUEST_HEADER_ERROR是自定义的,要用自己定义一个
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionConfig {
@ExceptionHandler(ApiHeaderErrorException.class)
public ResponseError headerError(ApiHeaderErrorException ex) {
return ResponseError.REQUEST_HEADER_ERROR;
}
@ExceptionHandler(ApiRequestErrorException.class)
public ResponseError validationErrorHandler(ApiRequestErrorException ex) {
return ResponseError.REQUEST_PARAM_ERROR;
}
}