如何处理HttpServerErrorException?

时间:2017-03-30 05:09:12

标签: java spring https exception-handling

我目前正在使用java和spring boot来获得API授权。它取决于用户为了查看天气有效或无效而插入的值。如果它有效则基本上会显示数据。

主要问题

当用户在api的末尾输入错误的值时。我收到错误500"内部服务器错误"它停止我的春季申请。我想创建一个异常,它将捕获此错误,并吐出错误500而不是停止我的应用程序。即使错误的值,我希望我的应用程序继续运行。

错误

当用户输入错误的参数时,我收到错误

 org.springframework.web.client.HttpServerErrorException: 500 Internal Server Error 

如何覆盖它,以便即使用户输入了错误的数据,也不要破坏我的应用程序并继续运行。只需显示Null for data。

尝试处理

我能够允许我的应用程序继续运行以下代码

try {  //OauthRestTemplate exhanges credentials for api access
 } catch (HttpServerErrorException e ) {                
   e.getStatusCode();
   logger.info(e + "Server bypass, Continue running application");
    //allow application to continue running but does not display the actual message that would be on the api.
        }
  //output
   org.springframework.web.client.HttpServerErrorException: 500 Internal Server ErrorServer bypass, Continue running application

但我希望它通过状态500并在我使用错误参数的api时显示实际消息。我应该收到api上打印的相同值。以下示例

{"message":"Physical resource does not exist for mac address: D","code":"APRO-2001","timestamp":1490895756655,"type":"com.server.camp.framework.exception.ErrorResponse","status":"INTERNAL_SERVER_ERROR"}

1 个答案:

答案 0 :(得分:0)

我不知道这是否适用于您的问题(因为您尚未提供代码),但这可能有所帮助:

@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Order")  // 404
 public class OrderNotFoundException extends RuntimeException {
     // ...
 }

基本上可以将@ResponseStatus添加到类中的函数中,将值设置为适当的值(在您的情况下为INTERNAL_SERVER_ERROR,如图所示here)。

我希望这有帮助!如果没有,请提供您的代码。

也许这个关于春天异常处理的链接可能会有所帮助:https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc