美文网首页嘟嘟程序猿
SpringBoot--实战开发--统一异常处理(三十二)

SpringBoot--实战开发--统一异常处理(三十二)

作者: 无剑_君 | 来源:发表于2019-08-06 11:42 被阅读41次

一、Maven依赖

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

二、统一异常处理类

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 通用异常
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = Exception.class)
    public Result<Object> handleException(Exception e) {
        return Result.fail(ResultCode.SERVER_ERROR.getCode(),e.getMessage());
    }
    /**
     * 缺少请求参数
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error("缺少请求参数", e);
        return Result.fail(ResultCode.PARAM_CHECK_ERROR.getCode(),"缺少请求参数"+ e.getMessage());
    }

    /**
     * 参数解析失败
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error("参数解析失败", e);
        return Result.fail(ResultCode.PARAM_CHECK_ERROR.getCode(),"json数据格式不正确"+ e.getMessage());
    }

    /**
     * 参数验证
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("参数验证失败", e);
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String field = error.getField();
        String code = error.getDefaultMessage();
        String message = String.format("%s:%s", field, code);
        return Result.fail(ResultCode.PARAM_CHECK_ERROR.getCode(),message);
    }

    /**
     * 参数校验异常
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BindException.class)
    public Result handleBindException(BindException e) {
        log.error("参数绑定失败", e);
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String field = error.getField();
        String code = error.getDefaultMessage();
        String message = String.format("%s:%s", field, code);
        return Result.fail(ResultCode.PARAM_CHECK_ERROR.getCode(),message);
    }

    /**
     * 参数校验异常
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ConstraintViolationException.class)
    public Result handleServiceException(ConstraintViolationException e) {
        log.error("参数验证失败", e);
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        ConstraintViolation<?> violation = violations.iterator().next();
        String message = violation.getMessage();
        return Result.fail(ResultCode.PARAM_CHECK_ERROR.getCode(),message);
    }

    /**
     * 参数验证异常
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ValidationException.class)
    public Result handleValidationException(ValidationException e) {
        log.error("参数验证失败", e);
        return Result.fail(ResultCode.PARAM_CHECK_ERROR.getCode(),e.getMessage());
    }

    /**
     *  不支持当前请求方法
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.error("不支持当前请求方法", e);
        return Result.fail(ResultCode.PARAM_CHECK_ERROR.getCode(),"请求方法不支持");
    }

    /**
     * 不支持当前媒体类型
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public Result handleHttpMediaTypeNotSupportedException(Exception e) {
        log.error("不支持当前媒体类型", e);
        return Result.fail(ResultCode.PARAM_CHECK_ERROR.getCode(),"不支持当前媒体类型");
    }

    /**
     * 业务逻辑异常
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(BusinessException.class)
    public Result handleServiceException(BusinessException e) {
        log.error("业务逻辑异常", e);
        return Result.fail(e.getResultCode());
    }
    /**
     * 操作数据库出现异常:名称重复,外键关联
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(DataIntegrityViolationException.class)
    public Result handleException(DataIntegrityViolationException e) {
        log.error("操作数据库出现异常:", e);
        return Result.fail("操作数据库出现异常:字段重复、有外键关联等");
    }
}

说明:全局异常类
一定要在启动类上添加包扫描:

@ComponentScan(basePackages = "com.xtsz")

否则,捕获不到异常。

二、实体类

@Data
public class PageVO implements Serializable {
    @Range(min = 1, max = 999999, message = "页数不正确")
    @NotNull(message = "页数不正确")
    private Integer curPage;
    @Range(min = 1, max = 999999, message = "页数大小不正确")
    @NotNull(message = "页数不正确")
    private Integer pageSize;
}

三、控制器

    @ApiOperation(value = "产品类目分页查询", notes = "参数格式:page=1&limit=2 JSON格式:{\"page\":1,\"limit\":2}", httpMethod = "GET")
    @RequestMapping(value = "/findByPage", method = RequestMethod.GET)
    public  Result findByPage(@Valid @RequestBody PageVO pageVO) throws Exception {
        Result result=Result.fail();
        PageBean pageBean=productCategoryService.findByPage(pageVO);
        result.resultSuccess();
        result.setData(pageBean);
        return result;
    }

说明:
一定要添加类注解@Validated
与参数注解:@Valid

四、常用注解

import javax.validation.constraints.NotNull;

空检查
@Null       验证对象是否为null
@NotNull      验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty 检查约束元素是否为NULL或者是EMPTY.

Booelan检查
@AssertTrue     验证 Boolean 对象是否为 true  
@AssertFalse    验证 Boolean 对象是否为 false  

长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内  
@Length(min=, max=) 
验证字符串的长度是否在给定的范围之内,包含两端

日期检查
@Past        验证 Date 和 Calendar 对象是否在当前时间之前  
@Future     验证 Date 和 Calendar 对象是否在当前时间之后  
@Pattern    验证 String 对象是否符合正则表达式的规则

数值检查:建议使用在Stirng,Integer类型,不建议使用在int类型上,因为表单值为“”时无法转换为int,但可以转换为Stirng为"",Integer为null
@Min            验证 Number 和 String 对象是否大等于指定的值  
@Max            验证 Number 和 String 对象是否小等于指定的值  
@DecimalMax 被标注的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度
@DecimalMin 被标注的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度
@Digits     验证 Number 和 String 的构成是否合法  
@Digits(integer=,fraction=) 验证字符串是否是符合指定格式的数字,interger指定整数精度,fraction指定小数精度。

@Range(min=, max=) Checks whether the annotated value lies between (inclusive) the specified minimum and maximum.
@Range(min=10000,max=50000,message="range.bean.wage")
private BigDecimal wage;
@Valid递归的对关联对象进行校验, 如果关联对象是个集合或者数组,那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验.(是否进行递归验证)
@CreditCardNumber信用卡验证
@Email 验证是否是邮件地址,如果为null,不进行验证,算通过验证。
@ScriptAssert(lang= ,script=, alias=)
@URL(protocol=,host=, port=,regexp=, flags=)

相关文章

网友评论

    本文标题:SpringBoot--实战开发--统一异常处理(三十二)

    本文链接:https://www.haomeiwen.com/subject/pxunhqtx.html