gpt4 book ai didi

java - Spring Boot 自定义 HTTP 异常

转载 作者:太空宇宙 更新时间:2023-11-04 09:29:09 26 4
gpt4 key购买 nike

我有这个方法来处理所有请求 header 丢失的异常,但在一个 Controller 中预计会收到一个 json 作为正文。如果它是无效的 json 或为 null,则会抛出带有自定义消息的异常:

@ExceptionHandler(value = {ServletRequestBindingException.class, HttpMessageNotReadableException.class})
public final ResponseEntity<ErrorResponse> handleHeaderException(Exception ex) {
List<String> details = new ArrayList<>();
details.add(ex.getMessage());
return new ResponseEntity<>(new ErrorResponse("Bad Request", details), HttpStatus.BAD_REQUEST);
}

{ "message": "Bad Request", "details": [ "Required request body is missing: public org.springframework.http.ResponseEntity packages.fazerLogin(packages.BodyLogin) throws java.io.IOException" ] }

<小时/>

{ "message": "Bad Request", "details": [ "JSON parse error: Unexpected character ('\"' (code 34)): was expecting comma to separate Object entries; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('\"' (code 34)): was expecting comma to separate Object entries\n at [Source: (PushbackInputStream); line: 3, column: 3]" ] }

但我不想要像上面这样的长消息。只需“必需的请求正文”或“JSON 解析错误”就可以了。我想知道我能做什么。

我的 Controller :

@PostMapping(value = "v1/token", consumes = "application/json;charset=UTF-8")
public ResponseEntity<TokenOutputDto> doLogin(@RequestBody @Valid BodyLogin body) throws IOException {
return authenticationModel.auth(body.getEmail(), body.getPassword());
}

此外,我是否应该为每个可能的异常(HttpClientErrorException、HttpServerErrorException 等)创建一个 @ExceptionHandler 方法?这将是一个糟糕的做法,因为代码几乎会重复......

最佳答案

您可以通过以下方式在方法中处理这些异常处理程序:

@ExceptionHandler(value = {ServletRequestBindingException.class, HttpMessageNotReadableException.class})
public final ResponseEntity<ErrorResponse> handleHeaderException(Exception ex) {
List<String> details = new ArrayList<>();
if (ex instanceof IOException ) {
if (ex.getCause() instanceof JsonParseException) {
details.add("JSON parse error");
} else {
details.add("Required request body");
}
} else {
details.add(ex.getMessage());
}
return new ResponseEntity<>(new ErrorResponse("Bad Request", details), HttpStatus.BAD_REQUEST);
}

关于java - Spring Boot 自定义 HTTP 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57311817/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com