【问题标题】:JAVA - custom error response for invalid dataJAVA - 无效数据的自定义错误响应
【发布时间】:2017-12-31 15:05:20
【问题描述】:

我写了一个post 控制器来处理来自JSON 请求的日期。

现在,对于无效日期,它会返回一般 500 错误而没有说明。

(即“statusDate”:“2017-13-27”)

如何返回自定义错误消息而不是一般错误消息?

(即“'statusDate'中的无效日期”)

这是代码:

  public class CustomDateDeserializer extends JsonDeserializer<Date> {

    @Override
    public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        format.setLenient(false);
        String dateAsString = jp.getText();

        if (dateAsString.isEmpty())
            return null;

        try {
            Date date = format.parse(dateAsString);
            if (dateAsString.split("-")[0].length() != 4)
                throw new RuntimeException();
            return date;
        } catch (ParseException e) {
            throw new RuntimeException(e);  //Here is the exception I want to change
        }
    }

【问题讨论】:

  • 您的意思是更改异常文本? throw new RuntimeException("bananas", e); ?
  • 那种。问题是,即使我更改了文本,它也会返回一般异常 (500)。
  • 您应该从抛出 JsonProcessingException 开始。然后解析器,然后是框架,会知道这是一个 JSON 问题,并会返回相应的状态码。
  • 自定义错误应由通用处理程序处理。在那里你可以调整序列化过程。

标签: java json rest


【解决方案1】:

创建RuntimeException时只需传递一条消息:

try {
    Date date = format.parse(dateAsString);
    if (dateAsString.split("-")[0].length() != 4)
        throw new RuntimeException("Another custom message");
    return date;
} catch (ParseException e) {
    throw new RuntimeException("Your custom message", e);
}

【讨论】:

  • 你说的传递一个方法是什么意思?
  • 错字。应该是message。会解决的。
猜你喜欢
  • 1970-01-01
  • 2019-02-07
  • 1970-01-01
  • 2012-05-22
  • 2016-09-23
  • 1970-01-01
  • 2018-12-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多