Springboot global exception interceptor, friendly exception prompt

FHAdmin 2022-06-24 06:13:54 阅读数:615


1. add to config Configuration class

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;
* explain : Error exception interception processing
* author :FH Admin
* from fhadmin.cn
public class ExceptionConfiguration implements HandlerExceptionResolver {
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
ModelAndView mv = new ModelAndView(new MappingJackson2JsonView()); // return json
String exInfo = ex.toString().replaceAll("\n", "<br/>");
boolean status = exInfo.contains("Subject does not have permission");
exInfo = "[ You do not have access to this page ]" + exInfo;
}else {
System.out.println("============== Abnormal start =============");
System.out.println("============== End of exception =============");
mv.addObject("exception", exInfo);
mv.addObject("result", "exception");
return mv;

2. Throw an exception on the method of the logical class throws Exception, such as

 /** Delete
* @param out
* @throws Exception
public Object delete() throws Exception{
Map<String,String> map = new HashMap<String,String>();
String errInfo = "success";
map.put("result", errInfo); // Return results
return map;

3. The front-end page receives abnormal results

 // send out post Request submit save
xhrFields: {
withCredentials: true
type: "POST",
url: httpurl+'xxxx/delete',
data: {tm:new Date().getTime()},
success: function(data){
if("success" == data.result){
}else if ("exception" == data.result){
alert(" Module exception "+data.exception);// Display exception

copyright:author[FHAdmin],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/175/20210724115548448N.html