java业务逻辑统一异常处理
程序员文章站
2022-03-30 20:18:23
...
做项目的时候一般业务逻辑出错都会返回统一的格式给前端,所以统一异常处理是很通用的。
我这里异常报错的时候统一返回这样的格式给前端:
{
"code":状态码,
"message":错误描述
}
异常类如下:
ApplicationException类:
public class ApplicationException extends RuntimeException{
public ApplicationException(){
super("后台处理错误");
}
public ApplicationException(String message){
super(message);
}
public static ApplicationException create(Exception e){
String message = null;
if(e instanceof ApplicationException){
message = e.getMessage();
}
if(StringUtils.isNotBlank(message)){
return new ApplicationException(message);
}else{
return new ApplicationException();
}
}
}
ExceptionHandlers类:
@ControllerAdvice(annotations = RestController.class)
@ResponseBody
@Log4j2
public class ExceptionHandlers {
@ExceptionHandler(value = ApplicationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ExceptionResponse defaultErrorHandler(ApplicationException e) {
return new ExceptionResponse("400",e.getMessage());
}
}
ExceptionResponse类:
@Data
@AllArgsConstructor
public class ExceptionResponse implements Serializable {
private static final long serialVersionUID = 6454716920977964115L;
private String code;
private String message;
}
最后只需要在业务层抛出异常就可以了:
前端看到的格式: