Jax-RS自定义异常处理
使用JEE的好處之一是可用的組件確實是非常標(biāo)準(zhǔn)的。 在使用JAX-RS時,有時您需要控制如何處理異常并將其反饋給用戶。 默認(rèn)情況下,如果引發(fā)異常,您將得到一些可怕的HTTP 500內(nèi)部服務(wù)器異常,從而暴露Web服務(wù)的內(nèi)部故障。
考慮以下要點,該端點將用于基于ID查看用戶。
現(xiàn)在,該接口的實現(xiàn)類似于以下內(nèi)容,以完成實際獲取用戶的驢工作。
public final class UserWebServiceImpl implements UserWebService {@EJB private UserDao userDao;public Response getUser(final String userId) {final User user = userDao.getUser(userId);return Response.ok().entity(user).build();} }看起來不錯,但請考慮使用Query.getSingleResult來確定 userDao是否正在執(zhí)行某些實體業(yè)務(wù)邏輯,并且不存在具有此ID的用戶嗎?
根據(jù)JEE6 API文檔,您將收到一個NoResultException ,它將導(dǎo)致暴露內(nèi)部服務(wù)器異常的HTTP 500錯誤,這絕對是最終用戶不應(yīng)該看到的。 我們需要利用Jax-RS的異常處理!
首先,我們需要一個笨拙的異常對象,適當(dāng)命名,這將是我們實際拋出的對象,請考慮以下代碼。
public class UserWebServiceException extends Exception implementsSerializable {private static final long serialVersionUID = 1169426381288170661L;public UserWebServiceException() {super();}public UserWebServiceException(String msg) {super(msg);}public UserWebServiceException(String msg, Exception e) {super(msg, e);} }接下來,我們需要修改原始代碼以考慮到此異常,我在下面適當(dāng)?shù)匦薷牧嗽糢serWebService和關(guān)聯(lián)的實現(xiàn)。
@Path("/users") public interface UserWebService {@POST@Consumes({ MediaType.APPLICATION_JSON })@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })@Path("/{userId}")Response getUser(@PathParam("userId") String userId) throws UserWebServiceException; }public final class UserWebServiceImpl implements UserWebService {@EJB private UserDao userDao;public Response getUser(final String userId) throws UserWebServiceException {try {final User user = userDao.getUser(userId);} catch(NoResultException e) {throw new UserWebServiceException("User does not exist with id " + userId);}return Response.ok().entity(user).build();} }現(xiàn)在,當(dāng)找不到用戶時,這將引發(fā)適當(dāng)?shù)漠惓!?但是,我們?nèi)匀恍枰獎?chuàng)建一個Handler對象,以將該異常轉(zhuǎn)換為實際的JSON響應(yīng),以便獲得友好的錯誤消息。 下面的類處理此異常,并將異常中的錯誤消息轉(zhuǎn)換為JSON響應(yīng)。 您將在此類上看到的重要注釋是@Provider注釋。
@Provider public final class UserWebServiceExceptionHandler implementsExceptionMapper<UserWebServiceException> {@Overridepublic Response toResponse(final UserWebServiceException exception) {return Response.status(Status.BAD_REQUEST).entity(new ErrorMessage(exception.getMessage())).type(MediaType.APPLICATION_JSON).build();} }您會注意到我們創(chuàng)建了一個ErrorMessage對象來響應(yīng)Web服務(wù)。 這只是一個簡單的啞對象,用于保存將編入JSON的實際錯誤的詳細信息。
public class ErrorMessage {private String error;public ErrorMessage(String error) {this.error = error;}public String getError() {return error;} }將異常處理程序提供程序映射到Web應(yīng)用程序的最后一步是將以下內(nèi)容添加到WebApp的web.xml中。
<context-param><param-name>resteasy.providers</param-name><param-value>uk.co.soa.rest.providers.UserWebServiceExceptionHandler</param-value> </context-param>現(xiàn)在,當(dāng)我們使用不存在的用戶ID調(diào)用REST端點時(假設(shè)為“ DAG”),我們將很高興收到以下JSON響應(yīng),而不是堆棧跟蹤。
{"error": "User does not exist with id DAG" }翻譯自: https://www.javacodegeeks.com/2014/05/jax-rs-custom-exception-handling.html
總結(jié)
以上是生活随笔為你收集整理的Jax-RS自定义异常处理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 向Java添加@atomic操作
- 下一篇: 用于JMX访问的Apache Ant任务