异常处理
通过使用@ControllerAdvice来进行统一异常处理,
@ExceptionHandler(value = RuntimeException.class)来指定捕获的Exception各个类型异常
package com.hb.common.exception; import com.hb.common.lang.Result; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.ShiroException; import org.springframework.http.HttpStatus; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.io.IOException; /** * 全局异常处理 * @Author shihb * @Date 2020/12/7 22:52 * @Version 1.0 */ @Slf4j @RestControllerAdvice public class GlobalExceptionHandler { /** * 捕捉shiro的异常 */ @ResponseStatus(HttpStatus.UNAUTHORIZED) @ExceptionHandler(ShiroException.class) public Result handle401(ShiroException e) { log.error("运行时异常:----------------ShiroException{}", e); return Result.fail(401, e.getMessage(), null); } /** * 处理Assert的异常 */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(value = IllegalArgumentException.class) public Result handler(IllegalArgumentException e) throws IOException { log.error("Assert异常:--------------ArgumentException>{}",e.getMessage()); return Result.fail(e.getMessage()); } /** * @Validated 校验错误异常处理 */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(value = MethodArgumentNotValidException.class) public Result handler(MethodArgumentNotValidException e) throws IOException { log.error("运行时异常:--------------ValidException>",e); BindingResult bindingResult = e.getBindingResult(); ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get(); return Result.fail(objectError.getDefaultMessage()); } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(value = RuntimeException.class) public Result handler(RuntimeException e) throws IOException { log.error("运行时异常:--------------RuntimeException>",e); return Result.fail(e.getMessage()); } }
其中实体类自定义的异常例子如下定义
@TableName("m_user") public class User implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Long id; @NotBlank(message = "昵称不能为空") private String username; @NotBlank(message = "邮箱不能为空") @Email(message = "邮箱格式不正确") private String email; ... }
接着用@Validated注解方式
如果实体不符合要求,系统会抛出异常 ,异常处理中就捕获到MethodArgumentNotValidException
如
/** * 测试实体校验 * @param user * @return */ @PostMapping("/save") public Object testUser(@Validated @RequestBody User user) { return user.toString(); }