Two methods and differences of spring boot handling global uniform exception

Time:2019-12-2

Preface

When an exception or request error occurs at the back end, the front end usually displays as follows

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Fri Jun 07 15:38:07 CST 2019
There was an unexpected error (type=Not Found, status=404).
No message available

It’s very unfriendly to users.

This article mainly explains how to use unified exception handling in spring boot applications.

Realization way

  • First, use @ controlleradvice and @ exceptionhandler annotations
  • The second is implemented by using the errorcontroller class.

First, use @ controlleradvice and @ exceptionhandler annotations

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

 @ResponseBody
 @ExceptionHandler(NullPointerException.class)
 public BaseResult globalException(HttpServletResponse response,NullPointerException ex){


 log.info("GlobalExceptionHandler...");
Log.info ("error code:" + response. Getstatus());
BaseResult result = new WebResult(WebResult.RESULT_FAIL,"request error:"+response.getStatus()
     ,"GlobalExceptionHandler:"+ex.getMessage());
 return result;
}

}

The @ controlleradvice annotation indicates that this is a controller enhancement class. When an exception occurs to the controller and meets the intercepting exception class defined in the class, it will be intercepted.

You can define the packet path of the intercepted controller


@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ControllerAdvice {
 @AliasFor("basePackages")
 String[] value() default {};

 @AliasFor("value")
 String[] basePackages() default {};

 Class<?>[] basePackageClasses() default {};

 Class<?>[] assignableTypes() default {};

 Class<? extends Annotation>[] annotations() default {};
}

Annotation exceptionhandler defines the intercepted exception class


@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExceptionHandler {
 Class<? extends Throwable>[] value() default {};
}

The second is implemented by using the errorcontroller class.

The default error handling class of the system is basicerrorcontroller, and the above error page will be displayed.

Write your own error handling class here. The default handling class above will not work.

The path server returned by geterrorpath() will be redirected to the corresponding processing class of the path, in this case, the error method.

@Slf4j
@RestController
public class HttpErrorController implements ErrorController {

 private final static String ERROR_PATH = "/error";

 @ResponseBody
 @RequestMapping(path = ERROR_PATH )
 public BaseResult error(HttpServletRequest request, HttpServletResponse response){
 Log.info ("access / error" + "error code:" + response. Getstatus());
 BaseResult result = new WebResult(WebResult.RESULT_FAIL,"HttpErrorController error:"+response.getStatus());
return result;
 }
 @Override
 public String getErrorPath() {
 return ERROR_PATH;
 }
}

test

The above defines a unified return class baseresult, which is convenient for front-end processing.

package com.microblog.common.result;

import java.io.Serializable;


public class BaseResult implements Serializable {

 private static final long serialVersionUID = 1L;

 public static final int RESULT_FAIL = 0;
 public static final int RESULT_SUCCESS = 1;

 //Return code
 private Integer code;

 //Return message
 private String message;

 //Return object
 private Object data;

 public BaseResult(Integer code, String message) {
  this.code = code;
  this.message = message;
 }

 public BaseResult(Integer code, String message, Object object) {
  this.code = code;
  this.message = message;
  this.data = object;
 }


 public Integer getCode() {
  return code;
 }

 public void setCode(Integer code) {
  this.code = code;
 }

 public String getMessage() {
  return message;
 }

 public void setMessage(String message) {
  this.message = message;
 }

 public Object getData() {
  return data;
 }

 public void setData(Object data) {
  this.data = data;
 }
}

Write a test controller


@Slf4j
@RestController
@RequestMapping("/user")
public class TestController {

 @RequestMapping("/info1")
 public String test(){
  log.info("/user/info1");

  throw new NullPointerException("TestController have exception");

 }
}

1. Issue a wrong request, that is, there is no corresponding processing class.

As you can see from the return, it is handled by the httperrorcontroller class


{"code":0,"message":"HttpErrorController error:404","data":null}

2. Issue a normal request (test() processing of testcontroller), and throw a null exception in the processing class

It can be seen from the return that it is handled by the globalexceptionhandler class


{"code":0,"message":"request error:200","data":"GlobalExceptionHandler:TestController have exception"}

Difference

1. Annotation @ controlleradvice mode can only handle exceptions thrown by the controller. The request is now in the controller.

2. The errorcontroller like mode can handle all exceptions, including errors not entering the controller, such as 404401 and other errors

3. If both exist in the application, the @ controlleradvice method will handle the exception thrown by the controller, and the errorcontroller like method will not enter the exception of the controller.

4. The @ controlleradvice method can define multiple interception methods, intercept different exception classes, and obtain the exception information thrown, with greater freedom.

summary

The above is the whole content of this article. I hope that the content of this article has some reference learning value for your study or work. Thank you for your support for developepaer.

Recommended Today

Manjaro uses SS method (requires nodejs environment)

Just installed manjaro, need to installshadowsocks-qt5+Proxy SwitchyOmega, but the latest Chrome has long blocked the installation of non Google store CRX channels. Here is my solution, which is troublesome but usable. If you are familiar with NPM commands in nodejs, you won’t find it troublesome, because nodejs is used for compilation. Preparation environment: A VPS […]