【发布时间】:2016-07-22 07:13:00
【问题描述】:
有没有使用 Rest api 在 JSON 中返回异常的简单方法?
我已经用谷歌搜索了这个问题,但我看到的所有解决方案都是关于在某些计算过程中抛出异常。但如果收入参数错误怎么办?我的意思是如果有一个字符串而不是 int 输入参数怎么办?
我为输入数据创建了一些 DTO 类:
@XmlRootElement
public class RequestDTO implements Serializable{
private static final long serialVersionUID = 1L;
@XmlElement(name = "request_id")
private String requestId;
@XmlElement(name = "site")
private List<String> sitesIds;
@XmlElement(name = "date_begin")
@JsonSerialize(using = DateSerializer.class)
@JsonDeserialize(using = DateDeserializer.class)
private Date dateBegin;
@XmlElement(name = "date_end")
@JsonSerialize(using = JsonDateSerializer.class)
@JsonDeserialize(using = JsonDateDeserializer.class)
private Date dateEnd;
@XmlElement(name = "volume")
private double volume;
// there is getters and setters
}
如果我在我的 json 请求中发送了类似“qwerty”而不是“volume”字段的内容,我会看到类似 Runtime 的错误消息。是否有可能以某种方式处理它?我的意思是用这种结构在json中返回错误?
public class ExceptionDTO {
private String shortExceptionMessage;
private String stackTrace;
public ExceptionDTO(String shotExceptionMessage, String stackTrace){
this.shortExceptionMessage = shotExceptionMessage;
this.stackTrace = stackTrace;
}
public String getShortExceptionMessage() {
return shortExceptionMessage;
}
public String getStackTrace() {
return stackTrace;
}
}
UPD1:
@Provider
@Singleton
public class ExceptionMapperProvider implements ExceptionMapper<Exception>{
@Override
public Response toResponse(final Exception e) {
StringBuilder trace = new StringBuilder();
IntStream.range(0, e.getStackTrace().length)
.forEach(i -> trace.append(e.getStackTrace()[i]).append('\n'));
ExceptionDTO exceptionMessage = new ExceptionDTO(
e.toString(),
trace.toString()
);
return Response.status(500).entity(exceptionMessage).build();
}
}
【问题讨论】:
-
休息API?您使用的是哪个特定的 jax-rs 实现,所以我可以提供更具体的答案?
-
@geneqew,我在春季项目中使用球衣
标签: java json api rest exception