Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

spring boot - How to map and log exceptions but still have SpringBoot render the JSON response?

I want a global exception handler that

a) maps certain exceptions to HTTP response codes, maybe by translating e.g. NoSuchElementException to ResponseStatusException

b) adds logging depending on the exception, e.g. NullPointerException gets more verbose logging than NoSuchElementExceptions

c) uses the SpringBoot JSON error response i.e. { timestamp: ..., status: ..., error: ... }

I read

but most approaches, like @ExceptionHandler want me to provide the HTTP response body. I want to use the original SpringBoot JSON error message though which is probably made by the DefaultErrorAttributes class.

Any ideas?

question from:https://stackoverflow.com/questions/65598409/how-to-map-and-log-exceptions-but-still-have-springboot-render-the-json-response

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I finally figured out that the obvious solution with @ExceptionHandler does indeed work but I had to add server.error.message: always to get the exception message into the response as well! (the default is ok as it can contain sensitive information!)

Apart from that it looks like:

@RestControllerAdvice
class ExceptionHandlers {

   @ExceptionHandler
   fun handleAllErrors(e: Throwable, response: HttpServletResponse) {
      ...
      response.sendError(status, message)
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...