更改格式时间戳异常Spring

时间:2016-06-30 09:49:27

标签: java spring date exception

我正在使用带@ResponseStatus的spring来抛出这样的异常:

@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格式。谢谢你的帮助

2 个答案:

答案 0 :(得分:0)

您可以使用@ExceptionHandler并使用ISO 8601日期格式构建您自己的响应:

下面我附上了一个例子:

@Controller
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public class SomeController {
...
  @ExceptionHandler(TaskNotFoundException.class)
  @ResponseStatus(HttpStatus.NOT_FOUND)
  public @ResponseBody
   Map<String,Object> handleTaskNotFoundException(TaskNotFoundException tnfe,
                                           HttpServletRequest request, HttpServletResponse resp) {
     HashMap<String, Object> result = new HashMap<>();
     DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
     df.setTimeZone(TimeZone.getTimeZone("UTC"));
     String formattedDate = df.format(new Date());
     result.put("8601date", formattedDate);
     ...
     return result;
  }
}

答案 1 :(得分:0)

您可以使用@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

}

对于基于控制器的异常处理,您可以向任何控制器添加额外的@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