【问题标题】:How to handle HttpServerErrorException?如何处理 HttpServerErrorException?
【发布时间】:2017-08-23 20:32:59
【问题描述】:

我目前正在使用 java 和 spring boot 在 API 中获得授权。这取决于用户插入的值以查看 api 是否有效。如果有效,它将基本上显示数据。

主要问题

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

错误

当用户输入错误的参数时,我会在下面收到一个错误

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

我怎样才能覆盖它,这样即使用户输入了错误的数据,也不要破坏我的应用程序并继续运行。只需为数据显示 Null。

尝试处理

我能够使用下面的代码让我的应用程序继续运行

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"}

【问题讨论】:

  • @FarazDurrani 谢谢!明天我会在我的编程计算机上尝试。
  • 算了。该解决方案是不正确的。相反,看看这个:springinpractice.com/2013/10/07/…
  • 抱歉,这不是 StackOverflow 的工作方式。 “我想做 X,请给我提示和/或示例代码” 形式的问题被视为离题。请访问help center并阅读How to Ask,尤其是阅读Why is “Can someone help me?” not an actual question?
  • @JimGarrison 问题很明确,OP 需要帮助来完成任务。我不需要任何代码示例,只是一个提示将有助于回答我的问题。
  • 如果没有看到您的代码,没有人可以提供帮助。这个问题跑题了。

标签: java spring https exception-handling


【解决方案1】:

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

@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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多