java自定义的异常类
1、自定义异常类,需要继承 RuntimeException
@Data
public class EmployeeCheckException extends RuntimeException
{
private int code;
private String msg;
public EmployeeCheckException(String msg, int code)
{
this.code = code;
this.msg = msg;
}
public EmployeeCheckException(String msg)
{
this.code = DATA_PARAM_FAIL_CODE;
this.msg = msg;
}
}
2、和全局异常放在一起
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler
{
/**
* 异常处理方法,可以自定义异常
* @param request 请求
* @param e 异常
* @return 错误提醒
*/
@ResponseBody
@ExceptionHandler(value = Exception.class)
public String defaultErrorHandler(HttpServletRequest request, Exception e)
{
//输入参数不满足约束
if(e instanceof MethodArgumentNotValidException)
{
e.printStackTrace();
BindingResult result = ((MethodArgumentNotValidException) e).getBindingResult();
return ResponseJsonUtil.returnJson(result.getAllErrors().get(0).getDefaultMessage(), PsiInfo.BAD_REQUEST.code);
}
else if(e instanceof IllegalArgumentException)
{
e.printStackTrace();
return ResponseJsonUtil.returnJson(e.getMessage(), PsiInfo.BAD_REQUEST.code);
}
else if(e instanceof EmployeeCheckException)
{
return ResponseJsonUtil.returnJson(((EmployeeCheckException)e).getMsg(), ((EmployeeCheckException) e).getCode());
}
else
{
e.printStackTrace();
return ResponseJsonUtil.returnJson(PsiInfo.ERROR.name, PsiInfo.ERROR.code);
}
}
}
原创文章,作者:bd101bd101,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/277070.html