Spring Boot 自定义 Exception 的共同处理

285 阅读1分钟

Spring Boot 自定义 Exception 共同处理

开发过程中,会对自定义的 Exception 做共同的处理,Spring Boot 对于这种需求提供了方便的支持。

具体只需要两步:

  1. 自定义 Exception 类。
  2. 定义异常的共同处理类,该类需要添加 @ControllerAdvice 注解。
    类中的异常处理的方法需要添加 @ExceptionHandler 注解。
    @ExceptionHandler 注解的 value 为 自定义 Exception 类的 class。
    可以对不同的 Exception 添加不同的异常处理的方法,每个方法的 @ExceptionHandler 注解的 value 为相应的 Exception 类的 class 。

这样自定义的 Exception 被抛出时就会走共同的处理。
如果没有走共同的处理,应该是抛出的 Exception 在异常共同处理类的方法没有相应的处理方法。
可确认下 Exception 的类型和 @ExceptionHandler 注解的 value 是否一致。

自定义 Exception 类

HelloException.java

public class HelloException extends Exception {
    public HelloException() {}
}

WorldException.java

public class WorldException extends Exception {
    public WorldException() {}
}

Exception 的共同处理类

HelloExcpetionHandler.java

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class HelloExcpetionHandler {
    @ExceptionHandler(value = HelloException.class)
    @ResponseBody
    public Result<String> helloExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        Result<String> result = new Result<String>();
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        result.setResult("Hello Exception");
        return result;
    }
    
    @ExceptionHandler(value = WorldException.class)
    @ResponseBody
    public Result<String> worldExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        Result<String> result = new Result<String>();
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        result.setResult("World Exception");
        return result;
    }
}

返回结果的POJO

Result.java

import lombok.Data;

@Data
public class Result<T> {
    private T result;
}