【问题标题】:How to handle Internal Server Error in REST API using JAVA?如何使用 JAVA 处理 REST API 中的内部服务器错误?
【发布时间】:2015-02-14 16:01:12
【问题描述】:

我创建了一个类来处理服务调用期间抛出的运行时异常,我的代码是

@Override
public Response toResponse(WebApplicationException exception) {
    Response response=exception.getResponse();
    if(response.getStatus()==400)
        return Response.status(Response.Status.BAD_REQUEST).entity("Invalid data format. Please enter the data in xml format").build();
    else if(response.getStatus()==403)
        return Response.status(Response.Status.FORBIDDEN).entity("You are not authorize to access this resource").build();
    else if(response.getStatus()==500)
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Internal server error has occured.Please check wheather you have passed valid data or not").build();
    else if(response.getStatus()==404)
        return Response.status(Response.Status.NOT_FOUND).entity("Invalid url. Please enter a valid url").build();
    else if(response.getStatus()==415)
        return Response.status(Response.Status.UNSUPPORTED_MEDIA_TYPE).entity("Invalid media type. Please select the correct media type").build();
    else if(response.getStatus()==503)
        return Response.status(Response.Status.SERVICE_UNAVAILABLE).entity("Server is not available. Please try after some time").build();
    else
        return Response.status(Response.Status.OK).entity("").build();
}

我的问题是它处理服务调用期间的所有其他异常抛出,除了 INTERNAL SERVER ERROR。请帮助我如何在 REST 运行时处理 INTERNAL SERVER ERROR。

提前致谢

【问题讨论】:

  • 我想知道他们在我的问题中是否有任何错误,以便其他人给我 -ve 标记。给-ve打分的人是真的知道解决方案,或者只是看了之后才给的。如果他们知道解决方案,请回答我

标签: java web-services rest exception-handling


【解决方案1】:

我不知道您使用的是什么网络服务器,但只要它遵守JEE specs,您就可以在您的web.xml 中简单地处理它:


500错误代码>
/path/to/myErrorPage.html

【讨论】:

  • dot_SpOt 感谢您的评论,但我想知道如何在 REST 中处理以显示客户端内部服务器错误消息。我的代码适用于所有其他异常,但不适用于 INTERNAL SERVER ERROR。
  • 我不确定您是否引用了REST 的任何第三方库。但本身RESTRepresentational State Transfer (en.wikipedia.org/wiki/Representational_state_transfer) 的缩写,它本身是一个术语,但不是产品。
猜你喜欢
  • 2018-07-08
  • 2020-02-19
  • 1970-01-01
  • 2011-02-12
  • 2016-01-10
  • 2020-08-18
  • 2021-11-14
  • 2020-02-07
  • 2013-10-08
相关资源
最近更新 更多