springboot自定义全局异常,非空等参数校验异常

  @ApiOperation(value = "新增账号")
    @PostMapping("/addAccount")
    public Result<Object> addAccount(@Valid @RequestBody AddAccountVo vo) {
        usrAccountService.addAccount(vo);
        return Result.success(RespCode.SUCCESS);
    }


    @NotBlank(message = "mobile不能为空")
    @ApiModelProperty(value = "手机号")
    private String mobile;

    @ApiModelProperty(value = "邮箱")
    private String email;

    @ApiModelProperty(value = "部门名称-拼接")
    private String deptIdListName;

    @ApiModelProperty(value = "启动可见权限数据集合")
    @NotEmpty(message = "enabledList不能用空")
    private List<SsoClientAccountAddVo> enabledList;

    public List<SsoClientAccountAddVo> getEnable

 自定义全局异常处理类: 

@Order(-1000)
@Configuration
public class ExceptionHandler  implements HandlerExceptionResolver {

	private static Logger LOGGER = LoggerFactory.getLogger(ExceptionHandler.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
										 Exception ex) {
		ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
		HashMap<String, Object> result = new HashMap<>();
		result.put("success",false);
		if (ex instanceof ServiceException) {
			result.put("code", ((ServiceException) ex).getCode());
			result.put("msg", StringUtils.hasLength(((ServiceException) ex).getMsg())
					? ((ServiceException) ex).getMsg(): ex.getMessage() );
			if(StringUtils.hasLength(((ServiceException) ex).getData())){
				result.put("data", JSONObject.parse(((ServiceException) ex).getData()));
			}
			result.put("timestamp",System.currentTimeMillis());
			result.put("traceId",((ServiceException) ex).getTraceId());
			LOGGER.error("业务异常:" + (StringUtils.hasLength(((ServiceException) ex).getMsg())
					? ((ServiceException) ex).getMsg(): ex.getMessage()));
		}else if (ex instanceof MethodArgumentNotValidException) {
			result.put("code", 9999);
			result.put("msg", ((MethodArgumentNotValidException) ex).getBindingResult().getFieldError().getDefaultMessage());
			result.put("timestamp",System.currentTimeMillis());
			result.put("traceId", UUID.randomUUID().toString().replace("-", ""));
			LOGGER.info("参数异常RebuildServiceException:{}" , result);
		}  else {
			ex.printStackTrace();
			result.put("code", RespCode.END.getCode());
			result.put("msg", RespCode.END.getMsg());
			result.put("timestamp",System.currentTimeMillis());
			result.put("traceId", UUID.randomUUID().toString().replace("-", ""));
			LOGGER.error(RespCode.END.getMsg());
		}
		response.setContentType(MediaType.APPLICATION_JSON_VALUE);
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache, must-revalidate");
		try {
			modelAndView.addAllObjects(result);
		} catch (Exception e) {
			LOGGER.error("#与客户端通讯异常:" + e.getMessage(), e);
		}

		return modelAndView;
	}

自定义业务异常类

public class ServiceException extends RuntimeException {
	private static final long serialVersionUID = 3653415555548581494L;

	private String code;

	private String msg;

	private String data;

	private String traceId= UUID.randomUUID().toString().replace("-", "");

	private RespCode respCode;

	public RespCode getRespCode() {
		return respCode;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}

	public void setRespCode(RespCode respCode) {
		this.respCode = respCode;
	}

	@SuppressWarnings("unused")
	private ServiceException() {
	}

	public ServiceException(String msg, Throwable e) {
		super(msg, e);
		this.msg = msg;
	}

	public ServiceException(String msg) {
		super(msg);
		this.msg = msg;
	}

	public ServiceException(RespCode respCode) {
		super(respCode.getCode() + respCode.getMsg());
		this.code = respCode.getCode();
		this.msg = respCode.getMsg();
		this.respCode=respCode;
	}

	public ServiceException(String data, RespCode respCode) {
		super(respCode.getCode() + respCode.getMsg());
		this.code = respCode.getCode();
		this.msg = respCode.getMsg();
		this.data=data;
		this.respCode=respCode;
	}

	public ServiceException(RespCode respCode, Object... moreMsg) {
		super(respCode.getCode() + String.format(respCode.getMsg(), moreMsg));
		this.code = respCode.getCode();
		try {
			msg = String.format(respCode.getMsg(), moreMsg);
		} catch (Exception e) {
			msg = respCode.getMsg();
		}
	}
	public ServiceException(String data, RespCode respCode, Object... moreMsg) {
		super(respCode.getCode() + respCode.getMsg());
		this.code = respCode.getCode();
		try {
			msg = String.format(respCode.getMsg(), moreMsg);
		} catch (Exception e) {
			msg = respCode.getMsg();
		}
		this.data=data;
		this.respCode=respCode;
	}


	public String getTraceId() {
		return traceId;
	}

	public void setTraceId(String traceId) {
		this.traceId = traceId;
	}
/**
 * 统一返回结果
 *  @author: jly
 * @date: 2023/4/6
 */
public class Result<T> {
	private String code;
	private String msg;
	private String traceId;
	private Long timestamp;
	private T data;

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getTraceId() {
		return traceId;
	}

	public void setTraceId(String traceId) {
		this.traceId = traceId;
	}

	public Long getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(Long timestamp) {
		this.timestamp = timestamp;
	}

	public T getData() {
		return data;
	}

	public void setData(T data) {
		this.data = data;
	}

	public static <T> Result<T> success(T body) {
		Result<T> res = new Result<>();
		res.setCode(RespCode.SUCCESS.getCode());
		res.setMsg(RespCode.SUCCESS.getMsg());
		res.setData(body);
		res.setTraceId(UUID.randomUUID().toString().replace("-", ""));
		res.setTimestamp(System.currentTimeMillis());
		return res;
	}
	public static <T> Result<T> fail(T body) {
		Result<T> res = new Result<>();
		res.setCode(RespCode.SUCCESS.getCode());
		res.setMsg(RespCode.SUCCESS.getMsg());
		res.setData(body);
		res.setTraceId(UUID.randomUUID().toString().replace("-", ""));
		res.setTimestamp(System.currentTimeMillis());
		return res;
	}

}
/**
 * 返回结果码
 * * @author: jly
 * @date: 2023/4/6
 */
public enum RespCode {
	/**
	 * 操作成功
	 */
	SUCCESS("0000", "操作成功"),

	PARAM_ILLEGAL("0001", "参数[%s]非法,%s"),

	END("0002", "系统繁忙,请稍后再试"),

	PARAMETER_FAIL("0003", "参数缺失,%s"),

	;

	private String code;
	private String msg;

	RespCode(String code, String msg) {
		this.code = code;
		this.msg = msg;
	}

	public static RespCode getRespByCode(String code) {
		if (code == null) {
			return null;
		}
		for (RespCode resp : values()) {
			if (resp.getCode().equals(code)) {
				return resp;
			}
		}
		throw new IllegalArgumentException("无效的code值!code:" + code);
	}

	public String getCode() {
		return code;
	}

	public String getMsg() {
		return msg;
	}

	public boolean isSuccess(String code) {
		return Objects.equals(code, this.code);
	}
}
 
可能用到的依赖
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.2.0.Final</version>
</dependency>
<dependency>
    <groupId>fa.hiveware</groupId>
    <artifactId>hiveware-cmn-contract</artifactId>
    <version>1.0</version>
</dependency>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贾宝玉的贾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值