温馨提示×

SpringBoot中怎么处理异常

小亿
83
2024-04-18 15:01:10
栏目: 编程语言

在SpringBoot中处理异常可以通过编写一个全局异常处理器来实现。一般情况下,我们可以继承Spring的ResponseEntityExceptionHandler类,并重写handleException方法来处理异常。具体实现步骤如下:

  1. 创建一个全局异常处理器类,例如GlobalExceptionHandler。
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
        // 处理所有异常
        ErrorResponse errorResponse = new ErrorResponse("500", ex.getMessage());
        return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(NotFoundException.class)
    public ResponseEntity<Object> handleNotFoundException(NotFoundException ex, WebRequest request) {
        // 处理自定义异常
        ErrorResponse errorResponse = new ErrorResponse("404", ex.getMessage());
        return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
    }
}
  1. 定义一个自定义异常类,例如NotFoundException。
public class NotFoundException extends RuntimeException {

    public NotFoundException(String message) {
        super(message);
    }
}
  1. 在Controller中抛出异常。
@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        throw new NotFoundException("Resource not found");
    }
}

通过以上步骤,我们就可以在SpringBoot项目中统一处理异常,并返回统一的错误信息给客户端。在GlobalExceptionHandler中,我们可以定义不同的异常处理方法来处理不同类型的异常,以实现更细粒度的异常处理。

0