在SpringBoot中处理异常可以通过编写一个全局异常处理器来实现。一般情况下,我们可以继承Spring的ResponseEntityExceptionHandler类,并重写handleException方法来处理异常。具体实现步骤如下:
@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);
}
}
public class NotFoundException extends RuntimeException {
public NotFoundException(String message) {
super(message);
}
}
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
throw new NotFoundException("Resource not found");
}
}
通过以上步骤,我们就可以在SpringBoot项目中统一处理异常,并返回统一的错误信息给客户端。在GlobalExceptionHandler中,我们可以定义不同的异常处理方法来处理不同类型的异常,以实现更细粒度的异常处理。