Exception handling mechanism of SpringMVC

1 Introduction

There are two types of exceptions in the system: expected exceptions and runtime exceptions RuntimeException , the former obtains exception information by catching exceptions, and the latter

The authors mainly reduce the occurrence of runtime exceptions by standardizing code development and testing.

The Dao , Service , and Controller of the system are all thrown upward through throws Exception, and finally handed over by the SpringMVC front-end controller.

Exception handling is performed by the exception handler, as shown in the figure below:

2. Processing method

① Use the simple exception handler SimpleMappingExceptionResolver provided by Spring MVC

② Implement Spring's exception handling interface HandlerExceptionResolver to customize your own exception handler

2.1、SimpleMappingExceptionResolver

The value configures the jump view, which is still affected by the view resolver:

2.2. Customization

Custom implementation steps:

① Create an exception handler class to implement HandlerExceptionResolver

② Configure exception handler in spring-mvc.xml

③ Writing abnormal jsp pages

④ Test abnormal jump

2.3. Precautions

In Spring MVC, when you configure a custom exception handler Bean, Spring will automatically recognize and register it as an exception handler. This is done through the implementation of the HandlerExceptionResolver interface. Spring MVC will detect the HandlerExceptionResolver Bean in the container at startup and add it to the exception handler chain.

Specifically, when you define a class that implements the HandlerExceptionResolver interface in the Spring configuration file or use annotation configuration, such as the custom exception handler class MyExceptionResolver , Spring will scan this class during initialization and determine whether it is implemented. HandlerExceptionResolver interface. If so, add it to the exception handler chain so exceptions can be caught and handled while the app is running.

Guess you like

Origin blog.csdn.net/qq_60735796/article/details/132255718