1. Create Globalexceptionhandler.java, annotate @controlleradvice on the class, annotate @exceptionhandler on method (value = Exception.class), Exception.class means to intercept all exception information
Package Com.rick.common.handler;
Import Com.alibaba.fastjson.JSON;
Import Com.alibaba.fastjson.util.IOUtils;
Import Com.rick.common.ResultJson;
Import com.rick.common.exception.BusinessException;
Import Org.springframework.http.MediaType;
Import Org.springframework.web.bind.annotation.ControllerAdvice;
Import Org.springframework.web.bind.annotation.ExceptionHandler;
Import Org.springframework.web.servlet.ModelAndView;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Java.io.PrintWriter;
@ControllerAdvice
public class Globalexceptionhandler {
@ExceptionHandler (value = exception.class)
Public Modelandview Defaulterrorhandler (httpservletrequest request, httpservletresponse response, Object handler, Exception ex) {
Response.setcontenttype (Mediatype.application_json_utf8_value);
SYSTEM.OUT.PRINTLN ("===================== Global exception Information capture =======================");
String msg;
if (ex instanceof businessexception) {
msg = Ex.getmessage ();
} else {
msg = "Operation exception!";
}
Ex.printstacktrace ();
PrintWriter out = null;
try {
out = Response.getwriter ();
Out.print (Json.tojson (Resultjson.buildfailinstance (msg)). toString ());
} catch (Exception e) {
E.printstacktrace ();
} finally {
Ioutils.close (out);
}
return null;
}
}
2, test the exception information, in the Hellocontroller.java to create abnormal information
@RestController Public class Hellocontroller { @RequestMapping ("/hello") public String Hello () { System.out.println (1/0);//Manufacturing Exception message return "Hello world!" ; }}
3. Effect display
Access Http://localhost:8080/hello, background throws exception information
Page Display effect
170621. Global anomaly capture of springboot programming