【JAVA】Java中Spring Boot如何设置全局的BusinessException
    		       		warning:
    		            这篇文章距离上次修改已过426天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring Boot中,您可以通过创建自定义的@ControllerAdvice类来设置全局的业务异常处理器。以下是一个简单的示例:
import org.springframework.http.HttpStatus;
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.ResponseStatus;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
 
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
 
    // 处理所有的BusinessException
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public final Object handleBusinessException(BusinessException ex, WebRequest request) {
        // 返回自定义的错误信息
        ErrorResponse response = new ErrorResponse(ex.getErrorCode(), ex.getMessage());
        return response;
    }
 
    // 处理方法参数验证不通过的异常
    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
                                                                  HttpHeaders headers,
                                                                  HttpStatus status, 
                                                                  WebRequest request) {
        // 返回自定义的错误信息
        ErrorResponse response = new ErrorResponse("INVALID_PARAMETER", "Invalid request parameters");
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }
}
 
// 自定义的错误响应类
class ErrorResponse {
    private String errorCode;
    private String message;
 
    public ErrorResponse(String errorCode, String message) {
        this.errorCode = errorCode;
        this.message = message;
    }
 
    // Getters and Setters
}在这个示例中,GlobalExceptionHandler类通过@ControllerAdvice注解被标记为全局异常处理器。它有一个针对自定义BusinessException的异常处理方法和一个覆盖方法,用于处理方法参数验证失败的异常。这里的ErrorResponse类用于封装错误信息。
当你在控制器中抛出BusinessException时,Spring Boot会自动调用这个全局异常处理器中的handleBusinessException方法来处理这个异常,并返回自定义的错误信息。同样,如果方法参数验证失败,也会调用handleMethodArgumentNotValid方法返回相应的错误信息。
评论已关闭