在 Spring REST 中处理错误场景

Handling error scenarios in Spring REST

恕我直言,例外情况适用于特殊情况。如果场景可以无异常地处理,则不应抛出异常。

创建异常至少需要 1 毫秒,并且会影响性​​能。那么哪种方法是处理错误情况的最佳方式?

场景#1:

ResponseEntity createOrder(@RequestBody Order order){
 if(order.items == null)
   return ResponseEntity.badRequest().build();
 ...
}

场景#2: Spring 提供了 Error Handling for REST with Spring

中提到的 @ControllerAdvice 和 ResponseEntityExceptionHandler
ResponseEntity createOrder(@RequestBody Order order){
     if(order.items == null)
       throw new CustomException();
     ...
    }

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = { CustomException.class })
    protected ResponseEntity<Object> handleConflict(RuntimeException ex, WebRequest request) {
        String bodyOfResponse = "Error";
        return handleExceptionInternal(ex, bodyOfResponse, 
          new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
    }
}

嗯,在特定情况下,我会使用 Hibernate 进行验证,而不是让无效数据进入控制器。

 public class Order {
 ...
     @NotNull
     @NotEmpty
     private List<Integer> items;
 }

如果项目为空或 null(虽然在内部使用异常),它会自动创建 400 错误。

为了处理其他异常,我会像你那里那样使用 @ExceptionHandler,每个控制器或通过 @ControllerAdvice(全局捕获)。

Creating exception takes at least 1ms

异常很慢,但没那么慢。

我个人会选择方案 #2,因为它是集中式的。稍后您将能够更改该特定异常的响应代码或添加一些详细的日志记录。在性能场景#1 方面显然更快,但我会忽略时间差异