在 Spring Boot 中自定义异常类的步骤如下:

  1. 创建一个自定义异常类,继承自 Exception 或 RuntimeException。
public class CustomException extends RuntimeException {
    private int code;
    private String message;

    public CustomException(int code, String message) {
        super(message);
        this.code = code;
        this.message = message;
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }
}
  1. 在自定义异常类中添加构造方法,用于传递异常信息。

  2. 在控制器或服务中,抛出自定义异常。

@GetMapping("/user/{id}")
public User getUserById(@PathVariable Long id) {
    User user = userRepository.findById(id)
            .orElseThrow(() -> new CustomException(404, "User not found"));
    return user;
}
  1. 在全局异常处理中,捕获自定义异常并返回自定义异常信息。
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseEntity<ApiError> handleCustomException(CustomException ex) {
        ApiError apiError = new ApiError(ex.getCode(), ex.getMessage());
        return new ResponseEntity<>(apiError, HttpStatus.valueOf(ex.getCode()));
    }
}
  1. 在全局异常处理中,使用 @ExceptionHandler 注解捕获自定义异常,并使用 @ResponseBody 注解将异常信息返回给客户端。

  2. 在返回的异常信息中,可以包含自定义的错误码和错误信息。

以上就是 Spring Boot 中自定义异常类的步骤。

spring-boot 如何自定义异常类怎么写

原文地址: https://www.cveoy.top/t/topic/bqt3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录