part error and exception handling mechanism
1, Errors and exceptions
Error Exception
Error is often something that cannot be handled by the program (an error introduced by the user or a system error)
Exception is caused by the programmer and can be handled in the program. try catch / throws
Excellent handling mechanism
Question: how to deal with it? How to be excellent?
2, Treatment method
There are three types: data validation error, error page assignment, and global exception handling
1) Data validation error
a) Hibernate Validator's own functions
@NotNull @NotEmpty @NotBlank
@NotNull is not empty. It is widely used to judge the basic type. int double boolean
@NotBlank is not an empty string. It is widely used to judge string types
@NotEmpty content is not empty. It is widely used to judge collections. Map = new hashmap(); map.put("","");
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
@Data @AllArgsConstructor public class Guest { @NotBlank(message = "Guest name cannot be empty") private String name; @NotBlank private String role; }
public class GuestValidTest { public static void main(String[] args) { //Create a validator instance through Validation Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); //Create a bean that does not meet the requirements Guest guest = new Guest("",""); //Start validation receive validation results Set<ConstraintViolation<Guest>> violationSet = validator.validate(guest); for(ConstraintViolation violation : violationSet){ System.out.println(violation.getPropertyPath() + "," + violation.getMessage()); } } }
This is one of the modes of the verification framework,
"Normal mode" (traverse all attributes, and return if it does not meet the verification rules)
"Quick failure mode" (when traversing attributes, one does not comply with the verification rules, that is, it returns)
public class GuestValidTest { public static void main(String[] args) { //Create a validator instance through Validation (normal mode) Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); //Create an instance of the quick failure mode Validator validatorFastFail = Validation.byDefaultProvider().configure() .addProperty("hibernate.validator.fail_fast","true"). buildValidatorFactory().getValidator(); //Create a bean that does not meet the requirements Guest guest = new Guest("",""); //Start validation receive validation results Set<ConstraintViolation<Guest>> violationSet = validator.validate(guest); for(ConstraintViolation violation : violationSet){ System.out.println(violation.getPropertyPath() + "," + violation.getMessage()); } System.out.println("=============================="); Set<ConstraintViolation<Guest>> violationFastFailSet = validatorFastFail.validate(guest); for(ConstraintViolation violation : violationFastFailSet){ System.out.println(violation.getPropertyPath() + "," + violation.getMessage()); } } }
b) Integrated use in springboot
Use default handling
@RestController public class GuestController { /** * @Valid Put it directly in front of the bean * Used to verify whether it complies with annotation rules * If the verification fails, 400 and the failure reason are returned directly * The processing method is to traverse all attributes and return all failed results * @param guest * @return */ @PostMapping("/guest") public String add(@Valid Guest guest){ return "Success"; } }
Custom effects are handled by ult
@PostMapping("/guest") public String add(@Valid Guest guest, BindingResult result){ if(result.getErrorCount()>0){ List<FieldError> fieldErrorList = result.getFieldErrors(); StringBuffer stringBuffer = new StringBuffer(); for(FieldError fieldError : fieldErrorList){ stringBuffer.append(fieldError.getField()); stringBuffer.append("\t"); stringBuffer.append(fieldError.getDefaultMessage()); stringBuffer.append("\n"); } return stringBuffer.toString(); } return "Success"; }
springboot supports setting verification information through the configuration file. The file name is ValidationMessages.properties. The location is under resources. Obtain the corresponding value through {key} in the annotation attribute in the bean
@NotBlank(message = "{guest.name.notblank}") private String name;
guest.name.notblank=Guest name cannot be empty from properties
2) Error page assignment
Mode 1:
Create a / public/error/404.html page. Note that only static pages are supported
Mode 2:
Create a / templates/error/404.html page that supports dynamic pages and has a higher priority than the / public/error directory.
Note: you can use 4xx.html page to represent the pages to be searched for all error codes starting with 4 (400401402...), and 5xx.html is the same.
When 404.html and 4xx.html exist at the same time, the accurate error code page is preferentially displayed, that is, 404.html
Mode 3: (priority is higher than mode 2)
Create a custom error view parser and implement the ErrorViewResolver interface
/** * Important: a bean needs to be processed by the spring container to take effect */ @Component public class MyErrorViewResolver implements ErrorViewResolver { @Override public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) { if(status.equals(HttpStatus.NOT_FOUND)){ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("/resolver404"); return modelAndView; } return null; } }
Mode 4: (priority is higher than mode 3)
Use WebServerFactoryCustomizer to register bean s and specify different pages by changing the processing path of error codes.
@Configuration public class MyCustomizer { @Bean public WebServerFactoryCustomizer<ConfigurableWebServerFactory> customizer(){ return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() { @Override public void customize(ConfigurableWebServerFactory factory) { ErrorPage errorPage = new ErrorPage(HttpStatus.NOT_FOUND,"/error404"); factory.addErrorPages(errorPage); } }; } }
@Controller public class MyErrorController { @RequestMapping("/error404") public String error404(){ return "error404"; } }
3) Global exception handling
Listen for all exceptions in the controller through the @ ControllerAdvise annotation, execute the method of the @ ExceptionHandler annotation, and jump to the error page.
/* * The section is processed using the @ ControllerAdvice annotation (provided by spring 3. X) */ @ControllerAdvice public class MyExceptionHandler { @ExceptionHandler(Exception.class) public ModelAndView handler(Exception e){ ModelAndView mv = new ModelAndView(); mv.setViewName("/error"); mv.addObject("message",e.getMessage()); return mv; } }
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>ERROR</title> </head> <body> Here is/templates/error.html <br> Now there's an exception <p th:text="${message}">message</p> </body> </html>
test case
@RequestMapping("/testError") public String error() throws Exception{ throw new Exception("Test exception"); }