REST API 中的错误处理:最佳实践



我正在尝试开发一个基本上返回有关国家/地区的信息的 rest api。所以我的网址将是这样的

http://myrestservice/country/US

因此,当请求附带有效的国家/地区时,我的 REST 服务将为该国家/地区准备信息并准备名为countryInfo的对象并将其返回为

return  ResponseEntity.status(200).body(countryInfo);

现在说用户发送请求为 http://myrestservice/country/XX。在这种情况下,由于XX不是有效的国家,我已经发送了回复。我在不同的地方阅读,其中大多数只解释状态代码。我的问题是返回错误的最佳方法是什么。

  1. return ResponseEntity.status(404).body("Invalid Country");
  2. return ResponseEntity.status(404).body(myobject);//这里 myObject 将被null

  3. 准备一个班级说MyResponse.java如下。

    public class MyResponse {
    private String errorCode;
    private String errorDescription;
    private CountryInfo countryInfo 
    }
    

无论是否有错误,都返回此对象。如果存在错误集errorCodeerrorDescription字段具有正确的值,并将countryInfo设置为 null 且没有错误,则将errorCode设置为errorDescription并为空,并countryInfo数据。

以上哪个选项被认为是处理错误的标准方法。

你确实应该返回一个404,但你在身体中返回的内容取决于你。

有些人只是返回一个包含一些人类可读信息的 html 响应,但如果您希望您的 API 客户端获取有关 404 发生原因的更多信息,您可能还希望返回 JSON。

您应该使用标准application/problem+json,而不是使用自己的格式。这是一个非常简单的格式:

https://www.rfc-editor.org/rfc/rfc7807

您可以使用@ControllerAdvice来处理异常:

终端节点需要识别错误并引发错误:

@RequestMapping("/country/{code}")
public ResponseEntity<Country> findCountry(String code) {
Country country = this.countryRepository(code);
if(country == null) throws new IllegalArgumentException("Invalid country code: " + code);
return  ResponseEntity.status(200).body(country);
}

然后创建一个类来处理终结点的异常:

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = { IllegalArgumentException.class })
protected ResponseEntity<Object> handleConflict(RuntimeException ex, WebRequest request) {
String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse, 
new HttpHeaders(), HttpStatus.CONFLICT, request);
}
}

在那里,您必须定义状态代码以指示用户生成了哪种错误,409以指示存在冲突。

此外,您还可以在其中定义一个包含更多信息的正文,一个字符串或一个自定义对象,其中包含您通过文档提供给客户端的错误消息和描述。

您可以使用 Zalando Problem,这是一个实现 application/problem+json 的库。

https://github.com/zalando/problem

https://thecodingduck.blogspot.com/2023/01/best-practices-for-rest-api-design.html#standard_error

最新更新