gpt4 book ai didi

java - Spring Boot 抛出异常时不显示自定义错误

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

我对 Java/Spring 领域相当陌生,我正在尝试在我的 Spring Boot 应用程序中使用 @ControllerAdvice。 ControllerAdvice 捕获异常但不显示我的自定义响应。

以下是抛出异常的 RestController 的快照

ResponseEntity<MyClass> response = new ResponseEntity<MyClass>(HttpStatus.OK);

try {
response = restTemplate.exchange(url, HttpMethod.GET, entity, MyClass.class);
} catch (HttpClientErrorException ex) {
throw ex;
}catch (HttpServerErrorException ex) {
logger.debug(ex.getMessage() + " Server Status Code - " + ex.getStatusCode());
}
catch(Exception ex) {
logger.debug(ex.getMessage() + " Generic Exception ");
}

以下是@ControllerAdvice

@ControllerAdvice
public class GlobalExceptionHandler extends Exception {

@ExceptionHandler(HttpClientErrorException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse errorHandle(HttpClientErrorException ex) {

String responseBody = ex.getResponseBodyAsString();

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
ErrorResponse errorResponse = new ErrorResponse();
try {
errorResponse = mapper.readValue(responseBody, ErrorResponse.class);

} catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return errorResponse;
}
}

其他类

@JsonIgnoreProperties
public class ErrorResponse {
@JsonProperty("error")
public Error error;

@JsonProperty("version")
public String version;

}

public class Error {
@JsonProperty("code")
public String Code;

@JsonProperty("message")
public String Message;

public String getCode() {
return Code;
}

public void setCode(String code) {
Code = code;
}

public String getMessage() {
return Message;
}

public void setMessage(String message) {
Message = message;
}

}

使用POSTMAN时遇到的错误是

{
"timestamp": "2019-11-20T05:42:24.126+0000",
"status": 404,
"error": "Not Found",
"message": "400 Bad Request",
"path": "myApi/somecontroller"
}

我在浏览器上收到的错误如下

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue Nov 19 23:40:26 CST 2019
There was an unexpected error (type=Not Found, status=404).
400 Bad Request

有什么想法/建议为什么会出现这种行为吗?我期待 ErrorResponse 类的 JSON 表示。

更新

enter image description here

最佳答案

这不是异常,这是错误场景

尝试使用以下代码。

@RestController
public class IndexController implements ErrorController{

private static final String PATH = "/error";

@RequestMapping(value = PATH)
public String error() {
return "Error handling";
}

@Override
public String getErrorPath() {
return PATH;
}
}

Spring Boot默认注册BasicErrorController,需要重写

关于java - Spring Boot 抛出异常时不显示自定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58947567/

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