Spring Boot to learn the basics of unified exception handling

  • 2020-10-23 20:07:01
  • OfStack

preface

As mentioned in the previous article about form validation, you can get the wrong message if an error occurs, but the return value issue is not considered.

Controller mentioned above:


@RequestMapping(value = "/doRegister", method = RequestMethod.POST) 
public @ResponseBody User doRegister(@Valid User user, BindingResult result, Model model) { 
 if (result.hasErrors()) { 
 List<ObjectError> list = result.getAllErrors(); 
 for (ObjectError error : list) { 
  System.out.println(error.getDefaultMessage()); 
 } 
 return null; 
 } 
 System.out.println(" registered .."); 
 return user; 
} 

If the validation fails, we should not return null's, which would not be friendly to the front end.

Therefore, we should define the return format of unit 1:


public class ReturnType { 
 
 private int code; 
 private User data; 
 private String msg; 
 
 public ReturnType(int code, String msg, User data) { 
 this.code = code; 
 this.msg = msg; 
 this.data = data; 
 } 
 
 public int getCode() { 
 return code; 
 } 
 public void setCode(int code) { 
 this.code = code; 
 } 
 public User getData() { 
 return data; 
 } 
 public void setData(User data) { 
 this.data = data; 
 } 
 public String getMsg() { 
 return msg; 
 } 
 public void setMsg(String msg) { 
 this.msg = msg; 
 } 
 
} 

In this way, the format of json in the returned result is fixed.

While our hope is good, this is not always the case, because both the underlying database operations, the business layer processes, and the control layer processes will inevitably encounter all kinds of predictable, unpredictable exceptions that need to be handled.

If the following situation exists:


@RequestMapping(value = "/doRegister", method = RequestMethod.POST) 
public @ResponseBody ReturnType doRegister(@Valid User user, BindingResult result, Model model) throws Exception { 
 throw new Exception("new Exception"); 
} 

This is like calling the Service layer and encountering an exception during the execution of the method. What does the result look like?
In any case, the return value is definitely not in the format we defined earlier.

So what should we do?

This is where exception handling for unit 1 comes in.


@ControllerAdvice 
public class ExceptionHandle { 
 
 /*  Indicates that the handler What types of exceptions are handled only  
 * */ 
 @ExceptionHandler(value = Exception.class) 
 //  The return value is json Or some other object  
 @ResponseBody 
 public ReturnType handle(Exception e) { 
 return new ReturnType(-1, e.getMessage(), null); 
 } 
} 

Create an handler class, and when Controller throws an exception, delegate execution to the methods in the class.

So the 1 doesn't happen, and even if it throws an exception, it doesn't get the return value that we're expecting.

conclusion


Related articles: