重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

springBoot中怎么自定义异常响应

这篇文章将为大家详细讲解有关springBoot中怎么自定义异常响应,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

创新互联主打移动网站、网站设计制作、网站设计、网站改版、网络推广、网站维护、空间域名、等互联网信息服务,为各行业提供服务。在技术实力的保障下,我们为客户承诺稳定,放心的服务,根据网站的内容与功能再决定采用什么样的设计。最后,要实现符合网站需求的内容、功能与设计,我们还会规划稳定安全的技术方案做保障。

1 自定义异常返回json数据、

//不要忘记添加 @ControllerAdvice

@ControllerAdvice

public class myExceptionHandler {

//浏览器和客户端返回的都是json

// @ResponseBody

@ExceptionHandler(UserNotExist.class)

public Map handlerException(Exception e){

   Map map = new HashMap<>();
   
   map.put("code","user.notexist");
   
   map.put("message",e.getMessage());
   
   return map;

} }

2 转发到/error下,进行自适应响应 @ControllerAdvice public class myExceptionHandler {

//浏览器和客户端返回的都是json

@ExceptionHandler(UserNotExist.class)

public String handlerException(Exception e, HttpServletRequest request){

    Map map = new HashMap<>();
	
    request.setAttribute("javax.servlet.error.status_code",500);
	
    map.put("code","user.notexist");
	
    map.put("message",e.getMessage());
	
    request.setAttribute("ext",map);
	
    return "forward:/error";
	
}

}

3 将定制的错误携带出去 @Component

public class myErrorAtrributes extends DefaultErrorAttributes {

//WebRequest webRequest,注意1.x.x版本的写法与2.1.0写法不同,我的是2.1.0

public Map getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {

    Map errorAttributes = super.getErrorAttributes(webRequest,includeStackTrace);
	
    errorAttributes.put("com", "maodong");
	
    Map ext= (Map) webRequest.getAttribute("ext",0);
	
    errorAttributes.put("ext",ext);
	
    return errorAttributes;
	
}

}

//为啥这么写:父类DefaultErrorAttributes类中的方法

public Map getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {

    Map errorAttributes = new LinkedHashMap();
	
    errorAttributes.put("timestamp", new Date());
	
    this.addStatus(errorAttributes, webRequest);
	
    this.addErrorDetails(errorAttributes, webRequest, includeStackTrace);
	
    this.addPath(errorAttributes, webRequest);
	
    return errorAttributes;
}

//为啥WebRequest webRequest能得到与低版本RequestAttrributes相同的结果

public interface WebRequest extends RequestAttributes {
@Nullable
String getHeader(String var1);

@Nullable
String[] getHeaderValues(String var1);

Iterator getHeaderNames();
------
}

//为啥  Map ext= (Map) webRequest.getAttribute("ext",0);能获得ext

public interface RequestAttributes {
int SCOPE_REQUEST = 0;
int SCOPE_SESSION = 1;
String REFERENCE_REQUEST = "request";
String REFERENCE_SESSION = "session";

@Nullable
Object getAttribute(String var1, int var2);

void setAttribute(String var1, Object var2, int var3);

void removeAttribute(String var1, int var2);

关于springBoot中怎么自定义异常响应就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


分享标题:springBoot中怎么自定义异常响应
文章地址:http://cqcxhl.cn/article/gpsddi.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP