创建统一信息返回类
public class Resp < T > {
private int code = 200 ;
private String msg = "success" ;
private T data;
private Resp ( int code, String msg, T data) {
this . code = code;
this . msg = msg;
this . data = data;
}
public static < T > Resp success ( T data) {
Resp resp = new Resp ( 200 , "success" , data) ;
return resp;
}
public static < T > Resp success ( String msg, T data) {
Resp resp = new Resp ( 200 , msg, data) ;
return resp;
}
public static < T > Resp error ( AppExceptionCodeMsg appExceptionCodeMsg) {
Resp resp = new Resp ( appExceptionCodeMsg. getCode ( ) , appExceptionCodeMsg. getMsg ( ) , null ) ;
return resp;
}
public static < T > Resp error ( int code, String msg) {
Resp resp = new Resp ( code, msg, null ) ;
return resp;
}
public int getCode ( ) {
return code;
}
public String getMsg ( ) {
return msg;
}
public T getData ( ) {
return data;
}
}
创建一个异常枚举类型
public enum AppExceptionCodeMsg {
INVALID_CODE ( 10000 , "验证码无效" ) ,
USERNAME_NOT_EXISTS ( 10001 , "用户名不存在" ) ,
USER_CREDIT_NOT_ENOUTH ( 10002 , "用户积分不足" ) ;
private int code ;
private String msg ;
public int getCode ( ) {
return code;
}
public String getMsg ( ) {
return msg;
}
AppExceptionCodeMsg ( int code, String msg) {
this . code = code;
this . msg = msg;
}
}
创建自定义的异常类
public class AppException extends RuntimeException {
private int code = 500 ;
private String msg = "服务器异常" ;
public AppException ( AppExceptionCodeMsg appExceptionCodeMsg) {
super ( ) ;
this . code = appExceptionCodeMsg. getCode ( ) ;
this . msg = appExceptionCodeMsg. getMsg ( ) ;
}
public AppException ( int code, String msg) {
super ( ) ;
this . code = code;
this . msg = msg;
}
public int getCode ( ) {
return code;
}
public String getMsg ( ) {
return msg;
}
}
创建全局统一异常处理类
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler ( value = { Exception . class } )
@ResponseBody
public < T > Resp < T > exceptionHandler ( Exception e) {
if ( e instanceof AppException ) {
AppException appException = ( AppException ) e;
return Resp . error ( appException. getCode ( ) , appException. getMsg ( ) ) ;
}
return Resp . error ( 500 , "服务器端异常" ) ;
}
}
创建controller测试异常处理
@RestController
public class DemoController {
@GetMapping ( "demo" )
public Resp < String > demo1 ( String name) {
if ( "ok" . equals ( name) ) {
return Resp . success ( "succ" ) ;
}
if ( "err" . equals ( name) ) {
throw new AppException ( AppExceptionCodeMsg . USERNAME_NOT_EXISTS ) ;
}
if ( "errcode" . equals ( name) ) {
throw new AppException ( AppExceptionCodeMsg . INVALID_CODE ) ;
}
if ( "0" . equals ( name) ) {
int i= 1 / 0 ;
}
if ( "notenough" . equals ( name) ) {
throw new AppException ( AppExceptionCodeMsg . USER_CREDIT_NOT_ENOUTH ) ;
}
return Resp . success ( "default" ) ;
}
@GetMapping ( "list" )
public Resp < List > list ( ) {
List < String > list = Arrays . asList ( "zhangsan" , "lisi" , "wangwu" ) ;
return Resp . success ( list) ;
}
}