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

编程入门 行业动态 更新时间:2024-10-19 20:27:28

springboot自定义全局<a href=https://www.elefans.com/category/jswz/34/1771210.html style=异常,非空等参数校验异常"/>

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);@Overridepublic 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>

更多推荐

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

本文发布于:2023-12-06 19:18:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1668545.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常   自定义   全局   参数   springboot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!