Springboot Unified exception handling for controller layer methods

Source: Internet
Author: User
Tags aop getmessage throwable

Controller layer method for uniform exception handling

Available in two different scenarios, as follows:

    1. Scenario 1: Use @ @ControllerAdvice (or @restcontrolleradvice), @ExceptionHandler annotation implementation;
    2. Scenario 2: implementation using AOP technology;

Now, respectively, introduce

Scenario 1: Use @controlleradvice and @ExceptionHandler @controlleradvice or @RestControllerAdvice @ControllerAdviceAnnotations to enhance all @RequestMappingmethod of marking;

Official explanation:
It is typically used to define @ExceptionHandler , @InitBinder and methods that apply to all @ModelAttribute @RequestMapping methods.

@ExceptionHandler
    • Only methods can be declared;
    • @ControllerAdvicecombined with, can be used to enhance @RequestMapping the exception handling of all methods;
Core code

For complete code, please refer to: Springboot uniform exception handling for controller layer methods

@RestControllerAdvice Public classControllerexceptionhandleadvice {Private Final StaticLogger Logger = Loggerfactory.getlogger (controllerexceptionhandleadvice.class); @ExceptionHandler Publicresultentity Handler (httpservletrequest req, httpservletresponse Res, Exception e) {logger.info ("Restful HTTP request has an exception ..."); if(Res.getstatus () = =HttpStatus.BAD_REQUEST.value ()) {Logger.info ("Modify return status value is 200");        Res.setstatus (HttpStatus.OK.value ()); }        if(Einstanceofnullpointerexception) {Logger.error ("Code 00:" +e.getmessage (), E); returnResultentity.fail ("A null pointer exception occurred"); } Else if(Einstanceofillegalargumentexception) {Logger.error ("Code 01:" +e.getmessage (), E); returnResultentity.fail ("Request parameter Type Mismatch"); } Else if(EinstanceofSQLException) {Logger.error ("Code 02:" +e.getmessage (), E); returnResultentity.fail ("Database access exception"); } Else{logger.error ("Code 99:" +e.getmessage (), E); returnResultentity.fail ("Server code exception, please contact Administrator"); }    }}

Scenario 2: Using AOP Technology

Full code: "AOP" Springboot uniform exception handling for controller layer methods

Core code
    • @Aspect annotations;
    • Weave in point:
    • The method return value is: resultentity
    • All methods of all classes below the package with controller hierarchy
    • @Around ("Execution (public com.ssslinppp.model.ResultEntity com). . Controller ... *(..))")
@Component @aspect Public classControlleraspect { Public Static FinalLogger Logger = Loggerfactory.getlogger (controlleraspect.class); @Around ("Execution (Public com.ssslinppp.model.ResultEntity com: *.controller. *.*(..))")     PublicObject Handlecontrollermethod (proceedingjoinpoint pjp) {Stopwatch Stopwatch=stopwatch.createstarted (); Resultentity<?>resultentity; Try{logger.info ("Execute controller start:" + pjp.getsignature () + "parameter:" +lists.newarraylist (Pjp.getargs ()). ToString ()); Resultentity= (resultentity<?>) Pjp.proceed (Pjp.getargs ()); Logger.info ("Execute controller end:" + pjp.getsignature () + ", return value:" +resultentity.tostring ()); Logger.info ("Time-consuming:" + stopwatch.stop (). Elapsed (Timeunit.milliseconds) + "(milliseconds)."); } Catch(Throwable throwable) {resultentity=handlerexception (PJP, throwable); }        returnresultentity; }    PrivateResultentity<?>handlerexception (Proceedingjoinpoint pjp, Throwable e) {resultentity<?> resultentity =NULL; if(Einstanceofruntimeexception) {Logger.error ("Runtimeexception{method:" + pjp.getsignature () + ", parameter:" + Pjp.getargs () + ", exception:" + e.getmessage () + "}", E); Resultentity=Resultentity.fail (E.getmessage ()); } Else{logger.error ("Exception {method:" + pjp.getsignature () + ", parameter:" + Pjp.getargs () + ", exception:" + e.getmessage () + "}", E); Resultentity=Resultentity.fail (E.getmessage ()); }        returnresultentity; }}

Springboot Unified exception handling for controller layer methods

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.