在 Spring Boot 中,统一异常处理是一种常见的做法,它可以让你集中处理应用程序中可能出现的各种异常,并为客户端提供一致的响应格式。
步骤 1: 创建异常类
首先,创建一些自定义异常类,以便在应用程序中抛出特定类型的异常。
// 自定义异常类
public class CustomException extends RuntimeException {
private final int statusCode;
private final String message;
public CustomException(int statusCode, String message) {
super(message);
this.statusCode = statusCode;
this.message = message;
}
public int getStatusCode() {
return statusCode;
}
public String getMessage() {
return message;
}
}
步骤 2: 创建全局异常处理器
接下来,创建一个全局异常处理器来捕获并处理各种异常。
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import