gpt4 book ai didi

java - Spring 更改格式时间戳异常

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

我使用 spring 和 @ResponseStatus 来抛出这样的异常:

@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Unknown task") 
public class TaskNotFoundException extends RuntimeException {

private static final long serialVersionUID = 1L;

private long taskId;

public TaskNotFoundException(long taskId) {
this.taskId = taskId;
}

public long getTaskId() {
return taskId;
}
}

我得到这样的回应:

{
"timestamp": 1467278537988,
"status": 404,
"error": "Not Found",
"exception": "com.TaskNotFoundException",
"message": "Unknown Task"
}

我想知道如何更改时间戳格式以获得 ISO 8601 格式。感谢您的帮助

最佳答案

您可以使用@ExceptionHandler@ResponseBody自定义错误响应。例如:

@ExceptionHandler(TaskNotFoundException.class)
@ResponseBody
@ResponseStatus(value = HttpStatus.NOT_FOUND)
private Message handleMessage(TaskNotFoundException e) {
Message message = new Message();
message.setTimestamp(ZonedDateTime.now().format(DateTimeFormatter.ISO_INSTANT));
message.setError("Not Found");
message.setStatus(404);
message.setException("com.TaskNotFoundException");
message.setMessage("Unknown Task");
return message;
}

Message 是一个简单的 POJO,用于保存错误响应正文。

public class Message {

private long timestamp;
private String error;
private int status;
private String exception;
private String message;

// getters and setters

}

对于基于 Controller 的异常处理,您可以向任何 Controller 添加额外的@ExceptionHandler方法来专门处理异常:

@Controller
class ExceptionHandlingController {

@ExceptionHandler(TaskNotFoundException.class)
@ResponseBody
@ResponseStatus(value = HttpStatus.NOT_FOUND)
private Message handleMessage(TaskNotFoundException e) {
...
}

}

对于全局异常处理,可以使用@ControllerAdvice:

@ControllerAdvice
class GlobalControllerExceptionHandler {

@ExceptionHandler(TaskNotFoundException.class)
@ResponseBody
@ResponseStatus(value = HttpStatus.NOT_FOUND)
private Message handleMessage(TaskNotFoundException e) {
...
}

}

更多详情请查看https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

关于java - Spring 更改格式时间戳异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38119556/

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