【问题标题】:Why does this JAVA endpoint not return a detailed error message to the client?为什么这个 JAVA 端点没有向客户端返回详细的错误消息?
【发布时间】:2020-07-30 02:45:38
【问题描述】:

我有一个 Java 服务器。如果我故意在 sql 查询中拼错一个单词,使其无效,则此函数会引发相应的错误。为什么这不会将详细的错误消息传递回客户端?相反,错误信息的范围只包括

“请求失败,状态码 500”

这是实际的详细错误:

错误:关系“联系人”不存在

这里是终点……

@POST
@Path("{from_list_id}/{to_list_id}")
public Message merge(@PathParam("from_list_id") int from_list_id, @PathParam("to_list_id") int to_list_id) {
    String sql = "select * from lists where list_id=?";

    sql = "insert into contacts (data, imported, list_id) select data, imported," + to_list_id
            + " from contacs where list_id = " + from_list_id;
    int rowsAffected = db.sql(sql).execute().getRowsAffected();
    return Message.success(
            "Successfully merged " + rowsAffected + " contacts");
}

我看到 dropwizard 在我的日志文件中捕获了确切的错误,但该错误没有发送到客户端。我们的客户端是一个使用 axios 的 Vuejs 组件。

这里是客户端 axios 调用

 this.$axios
    .post("/merge/" + this.from_list_id + "/" + this.to_list_id, {
      timeout: 0
    })
    .then(
      response => {
        this.list = response;
        util.showSuccess(response.data.message);
      },
      error => {
        console.log(JSON.stringify(error));
        util.showError(error);
      }
    );

【问题讨论】:

  • 您可以使用任何 DTO 来传播消息。 Drawback:- additional complexity
  • 因为 HTTP 状态 500 专门设计用于隐藏来自客户端的信息,以免将攻击向量泄露给攻击者。

标签: java vue.js error-handling axios


【解决方案1】:

您可以使用ControllerAdvice 做您想做的事,它的作用类似于全局异常处理程序,因此您可以处理任何类型的Exception 并返回您想要的内容

一个展示如何处理所有异常的例子:

@ControllerAdvice
public class ExceptionAdviceController {

    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<Map<String, Object>> handleBusinessException(HttpServletRequest req, Exception exception) {
        //you can return what you want here getCause(), getMessage() etc
        return new ResponseEntity<>(exception, 500);
    }
}

虽然您可以返回所有异常的详细信息,但您不应该这样做,因为这被认为是一种不好的做法。您应该处理特定类型并返回信息性消息和正确的 http 代码

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-31
    • 2018-08-22
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多