[英]How to intercept the error message when spring boot web binding?
I try to make user registration codes with spring boot web starter. 我尝试使用Spring Boot Web Starter制作用户注册代码。 First, these are registration form class including constraints. 首先,这些是包含约束的注册表单类。
@Data
public class RegisterForm {
@NotBlank(message = "Not valid username.") // (1)
@Size(min=2, max=30, message="minimum 2 and maximum 30") // (3)
private String username;
@NotBlank(message = "Not valid password") // (1)
@Size(min=5, message = "minimum 5") // (3)
private String password;
@Size(max=50, message="maximum 50") // (3)
private String fullname;
@NotEmpty(message = "Not valid email") // (2)
private String email;
}
And next codes are controller classes which bind User class and registration form class. 接下来的代码是绑定用户类和注册表单类的控制器类。
@RequestMapping(value="/users/register", method=RequestMethod.POST)
public String register(@Valid RegisterForm registerForm, Model model, BindingResult bindingResult) {
if(!bindingResult.hasErrors()) {
User user = new User();
user.setUsername(registerForm.getUsername());
user.setPassword(registerForm.getPassword());
user.setEmail(registerForm.getEmail());
user.setFullname(registerForm.getFullname());
user.setRole(UserRole.USER);
this.userService.register(user);
return "redirect:/home";
}
return "/users/register";
}
And Below codes are Error Controller class. 下面的代码是错误控制器类。
@RequestMapping("/error")
public String errorHandle(HttpServletRequest request) {
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
if(status != null) {
Integer statusCode = Integer.valueOf(status.toString());
if(statusCode.equals(HttpStatus.BAD_REQUEST.value())) {
return "/errors/400";
} else if(statusCode.equals(HttpStatus.NOT_FOUND.value())) {
return "/errors/404";
} else if(statusCode.equals(HttpStatus.FORBIDDEN.value())) {
return "/errors/403";
} else if(statusCode.equals(HttpStatus.INTERNAL_SERVER_ERROR.value())) {
return "/errors/500";
}
}
return "errors/default";
}
And I make the error intentionally ,and then the error message are brought on the console like below and 400 exception is thrown with /error/400 html. 并且我有意地犯了错误,然后将错误消息带到如下所示的控制台上,并用/ error / 400 html引发了400异常。
Field error in object 'registerForm' on field 'username': rejected value []; default message [minimum 2 and maximum 30]
Field error in object 'registerForm' on field 'username': rejected value []; default message [Not valid username]
Field error in object 'registerForm' on field 'email': rejected value []; default message [Not valid email]
Field error in object 'registerForm' on field 'password': rejected value []; default message [Not valid password]
Field error in object 'registerForm' on field 'password': rejected value [];default message [minimum 5]]
My issue is I have no idea how to send the field error of registerForm messages to /error/400 html so the user can confirm which field of registerForm violates the constraint. 我的问题是我不知道如何将registerForm消息的字段错误发送到/ error / 400 html,以便用户可以确认registerForm的哪个字段违反了约束。 I want to know how field error of registerForm can be transferred to /error/400 html. 我想知道registerForm的字段错误如何传输到/ error / 400 html。 Any idea, please. 任何想法,请。
first step: validate data in the controller like this 第一步:像这样验证控制器中的数据
@RequestMapping(value="/users/register", method=RequestMethod.POST)
public String register(@Valid RegisterForm registerForm)......
sencond step: make a controller advice which catch the exceptions 第二步:提出控制器建议以捕获异常
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = MethodArgumentNotValidException.class)
@ResponseBody
public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
//here you can use api of MethodArgumentNotValidException to do anything you want
//e.getBindingResult(),e.getFieldErrors(),etc;
// you can change the return type of Object
}
You need to extends ResponseEntityExceptionHandler
which provide centralized exception handling across all RequestMapping
methods. 您需要扩展ResponseEntityExceptionHandler
,以提供跨所有RequestMapping
方法的集中式异常处理。 This base class provides an ExceptionHandler
method for handling internal Spring MVC exceptions. 该基类提供了一个ExceptionHandler
方法,用于处理内部Spring MVC异常。 This method returns a ResponseEntity
for writing to the response with a HttpMessageConverter
message converter. 此方法返回一个ResponseEntity
用于使用HttpMessageConverter
消息转换器写入响应。
@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
// All Exceptions Handler.
@ExceptionHandler(Exception.class)
public final ResponseEntity<ExceptionBean> handleAllExceptions(Exception ex, WebRequest request) {...}
// Unique Constraint Violation Exception Handler.
@ExceptionHandler(DataIntegrityViolationException.class)
public final ResponseEntity<ExceptionBean> handleDataIntegrityViolationExceptions(DataIntegrityViolationException ex, WebRequest request) {...}
// Custom Exceptions Handler.
@ExceptionHandler(DomainException.class)
public final ResponseEntity<ExceptionBean> handleDomainExceptions(DomainException ex, WebRequest request) {
ExceptionBean exceptionBean = new ExceptionBean(new Date(), ex.getMessage(),
request.getDescription(false));
LOGGER.error(ex.getMessage(), ex);
return new ResponseEntity<>(exceptionBean, HttpStatus.BAD_REQUEST);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.