spring boot 异常拦截器全局友提示

发布时间:2022-06-08 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了spring boot 异常拦截器全局友提示脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

1. 添加config 配置类

package org.fh.config;
 
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.sPRingframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
 
/**
 * 说明:错误异常拦截处理
 * 作者:FH Admin
 * From fhadmin.cn
 */
@Configuration
public class ExceptionConfiguration implements HandlerExceptionResolver {
 
	@override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		ModelAndView mv = new ModelAndView(new MappingJackson2JsonView());	//返回json
		
		String exInfo = ex.toString().replaceAll("n", "<br/>");
		
		boolean status = exInfo.contains("Subject does not have PErmission");
		
		if(status){
			exInfo = "[没有此页面的访问权限]" + exInfo;
        }else {
        	System.out.println("==============异常开始=============");
    		ex.printStackTrace();
    		System.out.println("==============异常结束=============");
        }
		mv.addObject("exception", exInfo);
		mv.addObject("result", "exception");
		
		return mv;
	}
	
}

2.  在逻辑类的方法上抛出异常 throws Exception,比如  

	/**删除
	 * @param out
	 * @throws Exception
	 */
	@RequestMapping(value="/delete")
	@RequiresPermissions("autograph:del")
	@ResponseBody
	public Object delete() throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		//xxxx
		map.put("result", errInfo);				//返回结果
		return map;
	}

3. 前端页面接收异常结果

            //发送 post 请求提交保存
            $.ajax({
	            	xhrFields: {
	                    wIThCredentials: true
	                },
					type: "POST",
					url: httpurl+'xxxx/delete',
			    	data: {tm:new Date().getTime()},
					dataType:"json",
					success: function(data){
                        if("success" == data.result){
                        	
                        }else if ("exception" == data.result){
                        	alert("模块异常"+data.exception);//显示异常
                        	
                        }
                    }
				});            

 

脚本宝典总结

以上是脚本宝典为你收集整理的spring boot 异常拦截器全局友提示全部内容,希望文章能够帮你解决spring boot 异常拦截器全局友提示所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。