源码
自定义一个业务异常
@Data
public class DemoException extends RuntimeException {
private static final long serialVersionUID = 1 L;
private Integer code;
public DemoException ( ) { }
public DemoException ( ResultEnum resultEnum) {
super ( resultEnum. getMsg ( ) ) ;
this . code = resultEnum. getCode ( ) ;
}
}
错误码枚举
public enum ResultEnum {
UNKONW_ERROR ( - 1 , "未知错误" ) ,
SUCCESS ( 0 , "成功" ) ,
ERROR ( 10001 , "自定义业务异常信息" ) ,
;
private Integer code;
private String msg;
ResultEnum ( Integer code, String msg) {
this . code = code;
this . msg = msg;
}
public Integer getCode ( ) {
return code;
}
public String getMsg ( ) {
return msg;
}
public static String getMsg ( int code) {
for ( ResultEnum ele : values ( ) ) {
if ( ele. getCode ( ) . equals ( code) ) return ele. getMsg ( ) ;
}
return null;
}
}
统一返回格式的Result
@Data
public class Result {
private int code;
private int count = 0 ;
private String msg;
private Object data;
}
全局异常处理器
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler ( value = DemoException. class )
public ResponseEntity< ? > handlerException ( HttpServletRequest request, CustomerException e) {
Result error = new Result ( ) ;
if ( e instanceof DemoException ) {
log. info ( this . getClass ( ) + "业务异常:{}" , e. getMessage ( ) ) ;
error. setCode ( e. getCode ( ) ) ;
error. setMsg ( e. getMessage ( ) ) ;
return new ResponseEntity < > ( error, HttpStatus. OK) ;
}
error. setCode ( ResultEnum. UNKONW_ERROR. getCode ( ) ) ;
error. setMsg ( ResultEnum. UNKONW_ERROR. getMsg ( ) ) ;
return new ResponseEntity < > ( error, HttpStatus. OK) ;
}
}
测试一下
@RestController
@RequestMapping ( "test" )
public class TestContrller {
@GetMapping ( "/testError" )
public Result testError ( ) throws DemoException {
throw new DemoException ( ResultEnum. ERROR) ;
}
}
测试结果