SpringBoot学习之三,参数校验与全局异常处理

https://github.com/MaHanZhen/SpringBootStudy/tree/master/demo3

第一步,编写接收参数类

public class Student {

    @NotNull(message = "传入姓名为null")
    @NotEmpty(message = "传入姓名为空字符串")
    private String name;

    @NotNull(message = "传入成绩为null")
    @Min(value = 0,message ="成绩应大于0")
    @Max(value = 0,message ="成绩应小于100")
    private Integer score;

    @NotNull(message = "传入电话为null")
    @NotEmpty(message = "传入电话为空字符串")
    @Length(min = 11,max =11,message ="电话号码长度有误")
    private String mobile;
    //get,set
}

第二步,在请求处添加注解

//@Valid 注解 启用参数校验
    @RequestMapping("/testValid")
    public String testValid(@Valid Student student){
        System.out.println(student);
        return "success";
    }

测试


image.png

但是这里返回结果过于复杂,就需要使用过滤器

定义全局异常处理器

@ControllerAdvice //定义全局处理器
@ResponseBody
public class GlobalExceptionInterceptor {

    @ExceptionHandler(value = Exception.class)  //定义异常处理器
    public String exceptionHandler(HttpServletRequest request,Exception e) {
        String failMessage = null;
        
        //判断是否为绑定异常
        if(e instanceof BindException){
            BindException ex = (BindException)e;
             failMessage = ex.getBindingResult().getFieldError().getDefaultMessage();
        }
        return failMessage;
    }
}

测试

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容