Exception handling process
Execute the target method. Any exception during the running of the target method will be caught by catch
and mark the end of the current request. dispatchException
throws an exception
Enter the view parsing process and render the page. When an exception occurs, the parameter mv
is empty and the captured exception dispatchException## is passed in.
handler, and return
ModelAndView
HandlerExceptionResolvers and find the parser that can handle the current exception to resolve the exception
resolveExceptionResolve the exception, pass in the
request and
response objects, which method, the exception occurred, and then customize the exception handling to return
ModelAndView
DefaultErrorAttributesFirst handle the exception and The information is saved to the
request field and returned
null
##②
is used to process annotations@ExceptionHandler
Annotated method exception③
Used to handle method exceptions annotated with @ResponseStatus
④
Default processor exception parser, handles some common exceptions (4) If no parser can handle the exception, the exception will be thrown
(5) If no parser can handle the current exception, a
request will eventually be sent to forward the saved exception information to /error
. BasicErrorController
is specially used to handle /error
requests. BasicErrorController
will traverse all ErrorViewResolver
to parse error views. If there is no custom error view parsing The default DefaultErrorViewResolver
will be used, and the response code will be used as the address of the error page. The template engine will eventually respond to this page. Several exception handling methods and principles
1. Customize the error page,
error/404.html, error/5xx.html
. If there is an accurate error status code page, it will be matched accurately. If there is no page, look for 4xx.html
. If there is no page, it will trigger a white page. 2. Use
and @ExceptionHandler
handles global exceptions, the bottom layer is supported by ExceptionHandlerExceptionResolver
##3. Use @ResponseStatus
ResponseStatusExceptionResolver. The bottom layer calls
response.sendError(statusCode, resolvedReason), and Tomcat will receive an
error. At the end of the request, an empty
ModelAndView is returned, so that no processing parser can handle the current exception, and the
/error request will eventually be sent,
BasicErrorController is specially used to handle
/error requests and adapt to
4xx.html or
5xx.html pages
DefaultHandlerExceptionResolver that handles exceptions at the bottom of the framework. The bottom layer is also
response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE)
error. At the end of the request, an empty
ModelAndView is returned, so that no processing parser can handle the current exception, and the
/error request will eventually be sent,
BasicErrorController is specially used to handle
/error requests, adapting to
4xx.html or
5xx.html page
protected ModelAndView doResolveException( HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) { try { if (ex instanceof HttpRequestMethodNotSupportedException) { return handleHttpRequestMethodNotSupported( (HttpRequestMethodNotSupportedException) ex, request, response, handler); } else if (ex instanceof HttpMediaTypeNotSupportedException) { return handleHttpMediaTypeNotSupported( (HttpMediaTypeNotSupportedException) ex, request, response, handler); } else if (ex instanceof HttpMediaTypeNotAcceptableException) { return handleHttpMediaTypeNotAcceptable( (HttpMediaTypeNotAcceptableException) ex, request, response, handler); } else if (ex instanceof MissingPathVariableException) { return handleMissingPathVariable( (MissingPathVariableException) ex, request, response, handler); } else if (ex instanceof MissingServletRequestParameterException) { return handleMissingServletRequestParameter( (MissingServletRequestParameterException) ex, request, response, handler); } else if (ex instanceof ServletRequestBindingException) { return handleServletRequestBindingException( (ServletRequestBindingException) ex, request, response, handler); } else if (ex instanceof ConversionNotSupportedException) { return handleConversionNotSupported( (ConversionNotSupportedException) ex, request, response, handler); } else if (ex instanceof TypeMismatchException) { return handleTypeMismatch( (TypeMismatchException) ex, request, response, handler); } else if (ex instanceof HttpMessageNotReadableException) { return handleHttpMessageNotReadable( (HttpMessageNotReadableException) ex, request, response, handler); } else if (ex instanceof HttpMessageNotWritableException) { return handleHttpMessageNotWritable( (HttpMessageNotWritableException) ex, request, response, handler); } else if (ex instanceof MethodArgumentNotValidException) { return handleMethodArgumentNotValidException( (MethodArgumentNotValidException) ex, request, response, handler); } else if (ex instanceof MissingServletRequestPartException) { return handleMissingServletRequestPartException( (MissingServletRequestPartException) ex, request, response, handler); } else if (ex instanceof BindException) { return handleBindException((BindException) ex, request, response, handler); } else if (ex instanceof NoHandlerFoundException) { return handleNoHandlerFoundException( (NoHandlerFoundException) ex, request, response, handler); } else if (ex instanceof AsyncRequestTimeoutException) { return handleAsyncRequestTimeoutException( (AsyncRequestTimeoutException) ex, request, response, handler); } } catch (Exception handlerEx) { if (logger.isWarnEnabled()) { logger.warn("Failure while trying to resolve exception [" + ex.getClass().getName() + "]", handlerEx); } } return null; }
5. Custom implementation HandlerExceptionResolver
handles exceptions and can be used as the default global exception handling rule
@Order(value = Ordered.HIGHEST_PRECEDENCE) @Component public class CustomerHandlerExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { try { response.sendError(521,"I love you !"); } catch (IOException e) { e.printStackTrace(); } return new ModelAndView(); } }
ErrorViewResolver
Implement custom exception handling.
(1) When the bottom layer calls response.sendError
, the error
request will be forwarded to basicErrorController
by default, BasicErrorController
Specially used to handle /error
requests, adapting 4xx.html
or 5xx.html
pages
(2) If there is no parser for the exception It can be handled, and the bottom layer of tomcat will also call response.sendError
. error
The request will be forwarded to basicErrorController
by default, BasicErrorController
is specially used to handle /error
requests, adapting 4xx.html
or 5xx.html
page.
(3)basicErrorController
The page address you want to go to is determined by the ErrorViewResolver
error view resolver, that is, adaptation 4xx.html
Or 5xx.html
page.
The above is the detailed content of Analysis of the principles of SpringBoot exception handling. For more information, please follow other related articles on the PHP Chinese website!

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
