gpt4 book ai didi

spring-boot - Spring Boot自定义异常未在日志中打印

转载 作者:行者123 更新时间:2023-12-03 07:52:55 31 4
gpt4 key购买 nike

我正在尝试为我的Spring boot REST项目实现自定义异常。将调用自定义异常,但不会对错误消息的显示方式产生任何影响。

这是我用于自定义错误的POJO:

public class ApiError {
private HttpStatus status;
private String message;
private List<String> errors;

public ApiError(HttpStatus status, String message, List<String> errors) {
super();
this.status = status;
this.message = message;
this.errors = errors;
}

public ApiError(HttpStatus status, String message, String error) {
super();
this.status = status;
this.message = message;
errors = Arrays.asList(error);
}
}

这是我写的异常处理程序:

@ControllerAdvice
@EnableWebMvc
public class ApiExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
System.out.println("Custom exception!!");
//List<String> details = new ArrayList<>();
//details.add(ex.getLocalizedMessage());
//System.out.println("Localize message:: "+ex.getLocalizedMessage());
// ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(),

//request.getDescription(false));
ApiError error = new ApiError(HttpStatus.INTERNAL_SERVER_ERROR,"Server Error", request.getDescription(false));
return new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
}

此外,我在 Controller 中定义了以下方法:

@RequestMapping(value = "/model", params = "number", method = RequestMethod.GET, produces = "application/json")
List<Model> getModel(HttpServletRequest request,@RequestParam(value = "codeNumber") String number) throws Exception{

List<Model> model = null;
try {
model = niiService.getModel(number);
}catch(RuntimeException e){
new Exception(e);
}
return model;
}

但是,代替我的自定义POJO,我看到了以下异常:

{
"timestamp": 1547013989124,
"status": 500,
"error": "Internal Server Error",
"message": "Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure\n\nThe last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.",
"path": "/model"
}

我原本期望以下JSON结构:

{
"status": 500,
"message": "Server Error"
..
}

请让我知道,为了以我想要的方式获得错误响应,我缺少了什么。

最佳答案

您缺少自定义异常前面的throw
还要确保您在 Controller 内部捕获了正确的异常。

更改

catch (RuntimeException e) {
//custom exception
new Exception(e);
}


catch (RuntimeException e) {
//custom exception
throw new Exception(e);
}

关于spring-boot - Spring Boot自定义异常未在日志中打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54104242/

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