创建全局异常处理类:GlobalExceptionHandler
添加注解
@RestController
@ControllerAdvice
@Slf4j
import com.wallet.base.response.Result;
import com.wallet.base.response.ResultCode;
import com.wallet.base.response.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
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.RestController;
import javax.validation.constraints.NotNull;
/**
* 全局异常处理
*
* @author andyhoop
* @version create
* @since 2023-02-09
*/
@Slf4j
@RestController
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = Throwable.class)
@ResponseBody
public Result customExceptionHandler(@NotNull Throwable e) throws Throwable {
if (e instanceof CustomException) {
return Result.FAIL(((CustomException) e).getResultCode());
} else if (e.getCause() instanceof CustomException) {
CustomException ex = (CustomException) e.getCause();
return Result.FAIL(ex.getResultCode());
}else if (e instanceof MethodArgumentNotValidException){
String message = ((MethodArgumentNotValidException)e).getBindingResult().getFieldError().getDefaultMessage();
return Result.FAIL(ResultCode.PARAM_MISS.getCode(),message);
}
if (e instanceof BindException) {
log.error("GlobalExceptionHandler: {}", e.getMessage());
} else {
log.error("GlobalExceptionHandler", e);
}
throw e;
}
}
可以捕获自定义异常,只需要在if else判断中添加判断,之后捕获异常,处理自己的业务逻辑。
注意::由于我的项目是一个微服务项目,这个GlobalExceptionHandler 类我定义在common服务中,之后每个服务需要单独配置,配置方式:只需要在项目中创建一个如下配置类
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* 自动配置base beans
*
* @author andyhoop
* @version create
* @since 2023-02-09
*/
@Configuration
@ComponentScan(basePackageClasses = {com.wallet.base.interceptor.GlobalExceptionHandler.class})
public class BaseModuleConfig {
}