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);//顯示異常
}
}
});
本作品採用《CC 協議》,轉載必須註明作者和本文連結