1 .我们写业务代码的时候,经常使用异常处理,但是每次用try catch处理业务逻辑,看起来非常繁琐,代码冗长,否则后台会报告错误。 此时,您需要封装它,然后在处理代码时将一行代码返回到前台。
例外处理
@RestControllerAdvice注释的作用是阻止异常并统一处理
spring 3.2添加了@ControllerAdvice注释,可以定义@ExceptionHandler、@InitBinder和@ModelAttribute,并将其应用于所有@RequestMapping
创建RRExceptionHandler并添加@ControllerAdvice注释。
//*
* @ program :小精灵
* @描述:异常处理
* @author: Wu
* @ create :2020-08-2810336034
*/
@RestControllerAdvice
公共类rrexceptionhandler {
privateloggerlogger=logger factory.getlogger (getclass () );
//*
*处理自定义异常
*/
@ exception handler (RR exception.class ) )。
publicrhandlerrexception (rrexceptione ) {
R r=new R (;
r.put('code ',e.getCode ) );
r.put('msg ',e.getMessage ) );
返回r;
}
@ exception handler (nohandlerfoundexception.class ) )。
publicrhandlernofoundexception (exception e ) {
Logger.error(e.getmessage ),e );
returnr.error(404,'路径不存在。 请确认路径是否正确');
}
@ exception handler (duplicatekeyexception.class ) )。
publicrhandleduplicatekeyexception (duplicatekeyexceptione ) {
Logger.error(e.getmessage ),e );
return R.error (数据库中已存在此记录);
}
@ exception handler (authorization exception.class ) ) ) ) ) ) ) ) )。
publicrhandleauthorizationexception (authorizationexceptione ) {
Logger.error(e.getmessage ),e );
return R.error ('您没有权限。 请联系管理员获取许可证');
}
@ exception handler (exception.class ) )。
publicrhandleexception (exception e ) {
Logger.error(e.getmessage ),e );
return R.error (;
}
}
创建RRException类,继承RuntimeException类,并描述几种构造方法
package com.example.xiaowu.exception;
publicclassrrexceptionextendsruntimeexception {
privatestaticfinallongserialversionuid=1l;
私有字符串msg;
私有代码=500;
publicRRexception(stringmsg ) {
super(msg;
this.msg=msg;
}
publicRRexception(stringmsg,Throwable e ) {
super(msg,e );
this.msg=msg;
}
publicRRexception(stringmsg,int code ) {
super(msg;
this.msg=msg;
this.code=代码;
}
publicRRexception(stringmsg,int code,Throwable e )。
super(msg,e );
this.msg=msg;
this.code=代码;
}
公共字符串获取(
return msg;
}
publicvoidsetmsg(stringmsg ) {
this.msg=msg;
}
公共获取代码
返回代码;
}
公共码(intcode ) {
this.code=代码;
}
}
从接口返回的物理包r
package com.example.xiaowu.utils;
importorg.Apache.http.http status;
import java.util.HashMap;
import java.util.Map;
//*
* @ program :小精灵
* @description:返回数据
* @author: Wu
* @ create :2020-08-2810336039
*/
公共类r extends hashmap {
privatestaticfinallongserialversionuid=1l;
公共r () }
put(code ),0 );
put(msg,) success );
}
公共静态错误
returnerror (http status.sc _ internal _ server _ error,'未知异常。 请联系管理员')
}
publicstaticrerror (字符串msg ) {
returnerror (http status.sc _ internal _ server _ error,msg );
}
publicstaticrerror(intcode,String msg ) {
R r=new R (;
r.put (代码)、代码;
r.put(msg )、msg );
返回r;
}
公共静态锁定(string msg ) {
R r=new R (;
r.put(msg )、msg );
返回r;
}
public static ROK (地图) {
R r=new R (;
r.putall(map );
返回r;
}
公共静态锁定
返回新r (;
}
公共密钥(string key,Object value ) {
super.put(key,value );
return this;
}
}
接口测试
测试
返回值
返回值
承诺前端和代码,就能友好操作。