Remove "trace" field from ResponseStatusException

Pab*_*abi 3 spring-boot

In my spring controller I return a ResponseStatusException if no entity is found, like this:

@GetMapping("/categories/{id}")
  public ResponseEntity<Category> getCategoryById(@PathVariable(value = "id") String id) {
    try {
      return new ResponseEntity<Category>(categoryService.findById(id), HttpStatus.OK);
    } catch (CategoryNotFoundException ex) {
      throw new ResponseStatusException(HttpStatus.NOT_FOUND, ex.getMessage());
    }
  }
Run Code Online (Sandbox Code Playgroud)

I would expect the answer to be something like:

{
    "timestamp": "2019-02-22T12:25:29.913+0000",
    "status": 404,
    "error": "Not Found",
    "message": "could not find category with ID: XYZ'.",
    "path": "/categories/XYZ"
}
Run Code Online (Sandbox Code Playgroud)

But the response also includes a long field "trace" with the nested exception.
Is there a way to get rid of the trace field?

Kim*_*Man 54

打开application.properties并添加以下行:

server.error.include-stacktrace=never
Run Code Online (Sandbox Code Playgroud)


Dem*_*zer 10

我知道我参加聚会迟到了,但我最近遇到了这种情况并用另一个解决方案解决了,因为上述解决方案都不适合我的情况。

我正在使用Spring-boot-devtools,它会自动设置server.error.include-stacktrace=always

fillInStackTrace因此,我通过重写异常类中的方法来抑制堆栈跟踪,如下所示。

public class DuplicateFoundException extends RuntimeException {
    @Override
    public synchronized Throwable fillInStackTrace() {
        return this;
    }
}
Run Code Online (Sandbox Code Playgroud)

ps1:我参考了这篇文章。

ps2:您还可以尝试遵循其他答案中建议的解决方案:

(这些都不适用于我的情况)

如果您使用application.properties文件,请将以下行添加到您的属性文件中。

server.error.include-stacktrace=on_trace_param
Run Code Online (Sandbox Code Playgroud)

如果您使用的是application.ymlfile,请将以下行添加到您的 yml 文件中。

server:
  error:
    include-stacktrace: on_trace_param
Run Code Online (Sandbox Code Playgroud)

  • 喜欢你的解决方案,因为你可以有一个扩展 RuntimeExcepiton 的特定类,并且只从使用该类的异常中取出堆栈跟踪,而不是从其他可以保留它的异常中取出堆栈跟踪。 (2认同)

小智 6

如果您的依赖项中包含“ spring-boot-devtools”,则似乎存在“ trace”字段。排除devtools之后,我在输出中看不到这样的痕迹。

希望它会有所帮助。

  • 它只能在 application.properties 中使用“server.error.include-stacktrace=never”进行配置,如 @KimchiMan 答案中所述。 (5认同)

小智 5

spring-boot-devtools将属性设置server.error.include-stacktrace为always。

您可以保留devtools,但删除跟踪,并在其中添加以下内容application.yml:

server:
  error:
    include-stacktrace: on_trace_param
Run Code Online (Sandbox Code Playgroud)