Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of SpringMVC exception handling Mechanism and self-defined exception handling method

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces the example analysis of SpringMVC exception handling mechanism and custom exception handling, which is very detailed and has a certain reference value. Interested friends must read it!

When it comes to exception handling, we have to mention HandlerExceptionResolvers. Our DispatcherServlet has three exception handlers by default:

AnnotationMethodHandlerExceptionResolver: achieve exception resolution by annotated @ ExceptionHandler

ResponseStatusExceptionResolver: handle the status code exception of the HTTP request by annotating @ ResponseStatus

DefaultHandlerExceptionResolver: a client that processes Spring Exception and converts it to HTTP response status code delivery

Several kinds of exception ExceptionHTTP Status Code handled by SpringMVC by default

BindException

400 (Bad Request)

ConversionNotSupportedException

500 (Internal Server Error)

HttpMediaTypeNotAcceptableException

406 (Not Acceptable)

HttpMediaTypeNotSupportedException

415 (Unsupported Media Type)

HttpMessageNotReadableException

400 (Bad Request)

HttpMessageNotWritableException

500 (Internal Server Error)

HttpRequestMethodNotSupportedException

405 (Method Not Allowed)

MethodArgumentNotValidException

400 (Bad Request)

MissingServletRequestParameterException

400 (Bad Request)

MissingServletRequestPartException

400 (Bad Request)

NoHandlerFoundException

404 (Not Found)

NoSuchRequestHandlingMethodException

404 (Not Found)

TypeMismatchException

400 (Bad Request)

MissingPathVariableException

500 (Internal Server Error)

NoHandlerFoundException

404 (Not Found)

The first thing to introduce is the annotation @ ResponseStatus

@ ResponseStatus

Used on custom exception classes

This exception belongs to some kind of HTTP error status code exception (or left to handle)

For example, let's customize an exception class: HttpStateCode404Exception and map it to a 404 status code

Exception class: HttpStateCode404Exception.java

/ * * using @ ResponseStatus can only achieve a simple prompt * the prompt will be used when HttpStateCode404Exception is thrown in the program: page not found * / @ ResponseStatus (code=HttpStatus.NOT_FOUND,reason= "page not found") public class HttpStateCode404Exception extends RuntimeException {private static final long serialVersionUID = 1L;}

Then what we do when a Controller class handles the mapping path where / handleException/ exists.

Controller@RequestMapping ("handleException") public class HandleExceptionController {/ * @ ExceptionHandler ({Throwable.class}) public String handleThisController () {return "/ handleException/404";} * / @ RequestMapping ("{url}") public void handle404 () {throw new HttpStateCode404Exception ();}}

Careful readers will surely find that the code I noted above uses the @ ExceptionHandler annotation.

In the end, we can get the error page prompt like this: ugly, but with our reason

This method can only achieve simple information prompts.

Let's take a look at @ ExceptionHandler

Open the commented code above and you will find that our error control can jump to the page.

And because our method is defined in this Controller class, any exception that satisfies the @ ExceptionHandler definition will take this method.

Note: it is all requests in this Controller class that have exceptions, and the exceptions are contained in it

I want to define a global exception handling. @ ControllerAdvice

Handle all the exceptions of the controller Controllers for us

Concrete realization

/ * define an ExceptionHandler * / @ ControllerAdvicepublic class GlobalExceptionAdvice {@ ExceptionHandler ({HttpStateCode404Exception.class}) public String handleThisController () {return "/ handleException/404";} / * handle other exceptions. * /} exception handling order

1.Controller throws an exception during processing

two。 The @ ExceptionHandler in this Controller class executes its processing method if it is captured

3. Otherwise, it is handled by global exception catch

4. Otherwise, the exception catch handling of the @ ResponseStatus annotation

5. Finally, DefaultHandlerExceptionResolver processing

This is exactly the order in which DispatcherServlet exception handlers are configured (sequential calls, List)

Custom exception class (exception handling for SpringMVC)

Exception handling in SpringMVC-Custom exception handling Class

①: custom exception class public class CustomerException extends Exception {/ / define our exception information private String exceptMsg; public CustomerException (String exceptMsg) {this.exceptMsg = exceptMsg;} public String getExceptMsg () {return exceptMsg;} public void setExceptMsg (String exceptMsg) {this.exceptMsg = exceptMsg;}} ②: custom exception handler import java.io.PrintWriter;import java.io.StringWriter;import javax.jws.WebParam.Mode Import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.omg.CORBA.PRIVATE_MEMBER;import org.springframework.web.servlet.HandlerExceptionResolver;import org.springframework.web.servlet.ModelAndView Public class CustomerExceptionResolver implements HandlerExceptionResolver {@ Override public ModelAndView resolveException (HttpServletRequest request, HttpServletResponse response, Object handler,Exception ex) {/ / implement our exception handling through our custom exception handler and inherit from HandlerExceptionResolver / / customize our exception information String msg = "" / / use ModelAndView to jump to our error page, and bring the error message back to the page to display ModelAndView view = new ModelAndView (); view.setViewName ("error"); / / take out our custom exception information if (ex instanceof CustomerException) {CustomerException exception = (CustomerException) ex; msg = exception.getExceptMsg () } else {/ / get our stringWriter to get our exception information StringWriter writer = new StringWriter (); PrintWriter printWriter = new PrintWriter (writer); / / input exception information ex.printStackTrace (printWriter) into our printWriter through ex.printStackTrace (printWriter); msg = writer.toString () } / / after obtaining the exception information, notify the relevant personnel view.addObject ("msg", msg) through SMS, email and other technologies; return view;}} ③: configure our exception handlers. Above is all the contents of the article "sample Analysis of SpringMVC exception handling mechanisms and Custom exception handling methods". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report