The method __spring-Foundation of Controller layer Anomaly Unified treatment

Source: Internet
Author: User
Tags aop exception handling getmessage throwable
Controller layer method for unified exception handling controller layer method for unified exception handling

Two different scenarios are available, as follows: Scenario 1: Use @ @ControllerAdvice (or @restcontrolleradvice), @ExceptionHandler annotation Implementation, Scenario 2: Using AOP technology implementation;

Now introduce Scenario 1: Using @controlleradvice and @ExceptionHandler @ControllerAdvice or @RestControllerAdvice Use @controlleradvice annotations to enhance the methods of all @RequestMapping tags;

Official explanation:
It is typically used to define @ExceptionHandler, @InitBinder, and @ModelAttribute methods which apply to all @RequestMappi Ng methods. @ExceptionHandler can only declare methods, which can be used in conjunction with @controlleradvice to enhance exception handling of all @RequestMapping methods; Core Code

Complete code refer to: Springboot to the controller layer method for unified exception handling

@RestControllerAdvice public class Controllerexceptionhandleadvice {private final static Logger Logger = Loggerfactor

    Y.getlogger (Controllerexceptionhandleadvice.class);
        @ExceptionHandler Public resultentity 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 (e instanceof nullpointerexception) {logger.error ("code:" + e.getmessage (), E);
        return Resultentity.fail ("Null pointer exception occurred");
            else if (e instanceof illegalargumentexception) {logger.error ("code:" + e.getmessage (), E);
        return Resultentity.fail ("Request parameter Type mismatch");
            else if (e instanceof SQLException) {logger.error ("code:" + e.getmessage (), E);
        Return Resultentity.fail ("Database access exception");
      } else {      Logger.error ("code:" + e.getmessage (), E);
        Return Resultentity.fail ("The server code has an exception, please contact the Administrator"); }
    }
}
Scenario 2: Using AOP technology

Complete code: "AOP" springboot the core code @Aspect Annotation of the controller layer approach; Weaving point: The return value of the method is: resultentity all of the packages with controller levels below All methods of all classes @Around ("Execution" (Public com.ssslinppp.model.ResultEntity com ...). controller...* (..)) ")

@Component @Aspect public class Controlleraspect {public static final Logger Logger = Loggerfactory.getlogger (Control

    Leraspect.class); @Around ("Execution" (public com.ssslinppp.model.ResultEntity com. *.controller..
    *.*(..))")

        Public Object Handlecontrollermethod (Proceedingjoinpoint pjp) {Stopwatch stopwatch = stopwatch.createstarted ();
        Resultentity<?> resultentity; try {logger.info ("Execute controller start:" + pjp.getsignature () + "parameters:" + lists.newarraylist (Pjp.getargs ()). Tostrin
            g ());
            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) + "(ms);");
        catch (Throwable throwable) {resultentity = Handlerexception (PJP, throwable);
    return resultentity; Private resultentity<?> HandLerexception (Proceedingjoinpoint PJP, Throwable e) {resultentity<?> resultentity = null; if (e instanceof runtimeexception) {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 ());
    return resultentity; }
}

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.