spingboot全集异常处理和参数验证处理

1.新建ExceptionEnum枚举类

package com.common.config.exception;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
 * @Author DXZ
 * @Date 2020/11/6 11:18
 * @Version 1.0
 */
@Getter
@NoArgsConstructor
@AllArgsConstructor
public enum  ExceptionEnum {
    PRICE_CANNOT_NULL(400,"价格不能为空"),
    USER_NOT_FOUND(404,"用户未找到");

    private Integer code;
    private String msg;

}

 2.新建CommonException用户抛出异常

package com.common.config.exception;

import lombok.Getter;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

/**
 * @Author DXZ
 * @Date 2020/11/6 11:17
 * @Version 1.0
 */
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class CommonException extends RuntimeException {
    private ExceptionEnum exceptionEnum;
}

3.新建exceptionResult用户处理返回的结果集

package com.common.config.exception;


import lombok.Data;

/**
 * @Author DXZ
 * @Date 2020/11/6 11:35
 * @Version 1.0
 */
@Data
public class ExceptionResult {
    private Integer status;
    private String message;
    private Long timestamp;

    public ExceptionResult(ExceptionEnum e){
        this.status = e.getCode();
        this.message = e.getMsg();
        this.timestamp = System.currentTimeMillis();
    }

    public ExceptionResult(Integer status,String message){
        this.status = status;
        this.message = message;
        this.timestamp = System.currentTimeMillis();
    }
}

4.新建CommonExceptionHandler用户拦截Controller并进行异常处理和参数校验

package com.common.config.exception;

import cn.hutool.core.util.StrUtil;
import com.jfinal.kit.HttpKit;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.validation.ConstraintViolationException;

/**
 * @ClassName CommonExceptionHandler(默认会自动拦截所有的Controller)
 * @Description 异常处理类
 * @Author Dxz
 * @Date 2020/11/6 11:53
 * @Version 1.0
 */
@ControllerAdvice
public class CommonExceptionHandler {
    /**
     *
     * @param e
     * @return
     */
    @ExceptionHandler(CommonException.class)//拦截指定抛出的自定义CommonException异常
    public ResponseEntity<ExceptionResult> handleException(CommonException e) {
        return ResponseEntity.status(e.getExceptionEnum().getCode())
                .body(new ExceptionResult(e.getExceptionEnum()));
    }


    /**
     *拦截指定抛出的自定义MethodArgumentNotValidException异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ExceptionResult> handleException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sb = new StringBuilder();
        bindingResult.getAllErrors().forEach(error ->{
            String fieIdName = ((FieldError)error).getField();
            sb.append("[").append(fieIdName).append("]").append(error.getDefaultMessage()).append(";");
        });
        String str = StrUtil.format("参数未通过校验:{}", sb.toString());

        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(new ExceptionResult(HttpStatus.BAD_REQUEST.value(),str));
    }

    /**
     * 拦截指定抛出的自定义MissingServletRequestParameterException异常
     * @param e
     * @return
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)//拦截指定抛出的自定义MethodArgumentNotValidException异常
    public ResponseEntity<ExceptionResult> handleException(MissingServletRequestParameterException e) {
        String str = StrUtil.format("参数未通过校验:{}", e.getParameterName());

        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(new ExceptionResult(HttpStatus.BAD_REQUEST.value(),str));
    }

    /**
     * 拦截指定抛出的自定义ConstraintViolationException异常
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)//拦截指定抛出的自定义ConstraintViolationException异常
    public ResponseEntity<ExceptionResult> handleException(ConstraintViolationException e) {
        String str = StrUtil.format("参数未通过校验:{}", e.getMessage());

        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(new ExceptionResult(HttpStatus.BAD_REQUEST.value(),str));
    }










}

5.新建controller和service来进行测试异常抛出和参数校验

package com.user.web;


import com.common.config.exception.ExceptionResult;
import com.common.config.jfinal.model.User;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.user.config.constant.ApiConstants;
import com.user.dto.Params;
import com.user.service.AuthService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.ws.rs.FormParam;

/**
 * @Author DXZ
 * @Date 2020/10/30 10:58
 * @Version 1.0
 */
@RestController
@RequestMapping("auth")
@Slf4j
@Validated
public class AuthCtl {

    @Autowired
    AuthService authService;

    @PostMapping(value = "login")
    @ApiOperation(value = ApiConstants.AUTH_LOGIN, tags = {ApiConstants.AUTH_API}, response = String.class)
    public String pcLogin(
            @ApiParam(required = true,value = "用户名") @FormParam(value = "username") String username,
            @ApiParam(required = true,value = "密码") @FormParam(value = "password") String password
    ){
        Kv kv = new Kv();
        kv.set("username",username);
        kv.set("password",password);
        User user = User.dao.findFirst(Db.getSql("user.login"),kv);
        log.info("---进入登录方法---{}",user);
        return "";
    }


    @PostMapping(value = "postTest")
    @ApiOperation(value = "Post测试参数校验")
    public Object postTest(@RequestBody @Valid Params params){
        return authService.test();
    }

    @GetMapping(value = "getTest")
    @ApiOperation(value = "Get测试参数校验")
    //默认required = true为必填的,如果某个参数不需要必填,则设置required = false
    public Object getTest(@ApiParam(value = "用户名") @RequestParam(value ="name",required = false) String name,
                          @ApiParam(value = "年龄") @RequestParam(value ="age")@Max(100) Integer age){
        return authService.test();
    }
}
package com.user.service;

import com.alibaba.fastjson.JSON;
import com.common.config.exception.CommonException;
import com.common.config.exception.ExceptionEnum;
import com.common.config.exception.ExceptionResult;
import com.common.config.jfinal.model.User;
import org.springframework.stereotype.Service;

/**
 * @ClassName AuthService
 * @Description TODO
 * @Author Dxz
 * @Date 2020/11/6 11:56
 * @Version 1.0
 */
@Service
public class AuthService {
    public Object test(){
        User user = User.dao.findFirst("select * from t_user where user_id = ?","dxz1");
        if(null == user){
            throw new CommonException(ExceptionEnum.USER_NOT_FOUND);
        }
        return JSON.toJSONString(user);
    }

}
package com.user.dto;

import io.swagger.annotations.ApiModel;
import lombok.Data;

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

/**
 * @Author DXZ
 * @Date 2020/11/6 10:54
 * @Version 1.0
 */
@Data
@ApiModel(value = "参数校验")
public class Params {

    @NotBlank()
    private String name;
    @NotNull
    @Max(value = 100)
    private Integer age;
}