笔记,springboot参数校验@valid,异常处理

1.封装异常类统一处理

1.导入依赖


        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-aop
        
       
        
			io.springfox
			springfox-swagger2
			2.7.0
		
		
			io.springfox
			springfox-swagger-ui
			2.7.0
		
		
			org.projectlombok
			lombok
			1.18.0
		
		
		
			com.alibaba
			fastjson
			1.2.7
		
		
		
			org.springframework.boot
			spring-boot-devtools
			runtime
		

    

2.异常处理类

package com.battcn.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;
@ControllerAdvice
@Slf4j
public class RequestException {


	 /**
     * 对方法参数校验异常处理方法(仅对于表单提交有效,对于以json格式提交将会失效)
     * 如果是表单类型的提交,则spring会采用表单数据的处理类进行处理(进行参数校验错误时会抛出BindException异常)
     */
    @ExceptionHandler(BindException.class)
    public ResponseEntity handlerBindException(BindException exception) {
        return handlerNotValidException(exception);
    }
 
    /**
     * 对方法参数校验异常处理方法(前端提交的方式为json格式出现异常时会被该异常类处理)
     * json格式提交时,spring会采用json数据的数据转换器进行处理(进行参数校验时错误是抛出MethodArgumentNotValidException异常)
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity handlerArgumentNotValidException(MethodArgumentNotValidException exception) {
        return handlerNotValidException(exception);
    }
 
	public ResponseEntity handlerNotValidException(Exception e) {
        BindingResult result;
        if (e instanceof BindException) {
            BindException exception = (BindException) e;
            result = exception.getBindingResult();
        } else {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            result = exception.getBindingResult();
        }
        String desc = "";
        if (result.hasErrors()) {
            List fieldErrors = result.getFieldErrors();
            for (ObjectError error : fieldErrors) {
				//获取校验的信息
            	desc = error.getDefaultMessage();
			}
        } else {
        	desc = "系统异常";
        }
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestException().fail(desc));
    }

	public String fail(String desc) {
		Map map = new HashMap();
		map.put("code", "-1");
		map.put("desc", desc);
		return objectToJsonString(map);
	}
	public static String objectToJsonString(Object obj) {
		return JSON.toJSONString(obj);
	}
}

3.测试 entity

package com.battcn.entity;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

import com.battcn.annotation.IsMobile;

import lombok.Data;

@Data
public class UserEntity {
	
	@NotBlank(message="名称不可为空")
	private String userName;
	
	private String id;
	
	private String sex;

	@NotNull(message = "年龄不能为空")
	private String age;
	
	@NotNull(message = "手机号不可为空")
	private String mobilePhone;
	
	private String salary;
	
}

4.控制层

package com.battcn.controller;

import com.battcn.annotation.CacheLock;
import com.battcn.entity.UserEntity;

import javax.validation.Valid;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/books")
public class UserController {

    @RequestMapping(value = "create", method = RequestMethod.POST)
	public String create(@Valid @RequestBody UserEntity entity) throws Exception {
		try {
			return "sucess";
		} catch (Exception e) {
			throw new Exception(e);
		}
	}
    
	@RequestMapping(value = "search", method = RequestMethod.GET)
	public String search(@Valid  UserEntity entity) throws Exception {
		try {
			return "sucess";
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

}

 

 

 

 

 

你可能感兴趣的:(笔记,springboot参数校验@valid,异常处理)