我有一个枚举类:
class enum Type {
LOCAL, REMOTE
}
我有一个接受枚举作为 GET 参数的 API
@RequestMapping(method = RequestMethod.GET, location="item", params = "type")
public Item[] get(Type type) {
...
当客户端使用有效值调用 API 时,例如
GET /item?type=LOCAL
或 GET /item?type=REMOTE
它工作正常。如果客户端为 type
提供无效值,例如GET /item?type=INVALID_TYPE
,然后 Spring 生成 500 Internal Server Error
.我想把它变成400 Bad Request
验证错误,可能会为客户端添加有用的信息。我更喜欢重用内置的类型转换器,因为它工作得很好,只是想以最少的更改更改 HTTP 抛出的错误类型。
最佳答案
我相信,如果您将正确的异常(exception)添加到 @ControllerAdvice
,您可以自定义响应。在这种情况下,我发现 MethodArgumentTypeMismatchException
是有问题的那个。
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public void methodArgumentTypeMismatchException(final HttpServletResponse response) throws IOException {
response.sendError(BAD_REQUEST.value());
}
关于spring - Spring ConversionFailedException 错误 HTTP 状态的自定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35665024/