您可以映射此異常。爲什麼不?你有錯誤嗎?
此代碼應該做的工作
@Provider
public class EJBExceptionMapper implements ExceptionMapper<org.jboss.resteasy.spi.UnsupportedMediaTypeException>{
Response toResponse(org.jboss.resteasy.spi.UnsupportedMediaTypeException exception) {
return Response.status(415).build();
}
}
不要忘了申報在Spring配置文件提供者。
如果你希望提供給客戶更多的信息,創建一流
@XmlRootElement
public class Error{
private String message;
//getter and setter for message field
}
,然後你可以
@Provider
public class EJBExceptionMapper implements ExceptionMapper<org.jboss.resteasy.spi.UnsupportedMediaTypeException>{
Response toResponse(org.jboss.resteasy.spi.UnsupportedMediaTypeException exception) {
Error error = new Error();
error.setMessage("Whatever message you want to send to user");
return Response.entity(error).status(415).build();
}
}
如果你不想使用錯誤的實體簡單地傳遞一個字符串Response.entity()
呼叫。
如果你想趕上無論是在你的應用程序拋出創建通用的異常映射:
@Provider
public class ThrowableMapper implements ExceptionMapper<Throwable> {
public Response toResponse(Throwable t) {
ErrorDTO errorDTO = new ErrorDTO(code);
return Response.status(500).build();
}
}
我發現,如果異常的,即如果我作爲一個開發者選擇拋出的異常,業務邏輯拋出映射器的作品。但是,如果在內部拋出相同的異常,如果@Consumes註釋未能驗證內容類型,則不會調用映射器。 – Mustafa 2012-05-08 04:44:48
嘗試爲Throwable類創建異常映射器(請參閱更新的答案) – 2012-05-08 07:37:54