Recently, I want to do some exception handling for company projects. The usual approach is to use @ExceptionHandler to list all exceptions in an enumerated form, but from a design pattern perspective, this does not comply with the open close principle.

Then, I went to check how the Spring framework itself handles common exception throwing, specifically implemented in specifically: - org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler#handleException - org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#doResolveException

Unfortunately, their approach is also hard coded through @ExceptionHandler to list all.

So, I would like to inquire if it is possible to control the captured exceptions and the corresponding response content (including response headers and response bodies) through configuration。

I think the ideal approach is to configure it through .yaml or .application files, such as:

spring:
  web:
    exception:
      HttpRequestMethodNotSupportedException:
        httpStatus: 405
      HttpMediaTypeNotSupportedException:
        httpStatus: 415
      # The following are the exceptions defined in business development, such as:
      RequestCompanyApiException:
        httpStatus: 400
        bodyCode: 4000001
        bodyMessage: The code can not be empty
      CompanyApiInternalException:
        httpStatus: 500
        bodyCode: 5000001
        bodyMessage: Request for third-party interface timeout
      # ......
      OtherException:
        httpStatus: 500
        bodyCode: 5000000
        bodyMessage: There is a temporary issue with the system service, Please try again later 🥺

🤝 Looking forward to replies from coder with good ideas.

Comment From: snicoll

Thanks for the suggestion. There's no such feature and the core framework is not the right place to ask for something configurable like this. Your example above feels like programming by properties and I think it is better to have that in code rather than configuration. That said, you should be able to implement something that parse the configuration properties above quite easily.

If you were searching for guidance about that, please ask on StackOverflow, as mentioned in the guidelines for contributing, we prefer to use the issue tracker only for bugs and enhancements.