spring@ExceptionHandler注解⽅式实现异常统⼀处理⾸先,在我们的⼯程中新建BaseController⽗类,内容如下:
soft.ption;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ExceptionHandler;
/**
* 2015-11-06
*
* @author djw 统⼀异常处理,所有controler继承此类
*/
public abstract class BaseController {
@ExceptionHandler
public String handleException(HttpServletRequest request,
HttpServletResponse response, Exception e) {
printException(e);// log4j打印错误级别堆栈⽇志信息,时间
// json格式的ajax请求
if (Header("accept").indexOf("application/json") > -1
|| (Header("X-Requested-With") != null && request
.getHeader("X-Requested-With")
.indexOf("XMLHttpRequest") > -1)) {
response.setStatus(500);
response.setContentType("application/json;charset=utf-8");
try {
PrintWriter writer = Writer();
if (e instanceof RuntimeException) {// 运⾏时异常
writer.write("系统内部异常!");
} else {// ⾮运⾏时异常
writer.Message());// 此处待细化异常处理给提⽰???
}
writer.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return null;
} else {// URL普通请求
if (e instanceof RuntimeException) {// 运⾏时异常
spring framework runtimerequest.setAttribute("exceptionMessage", "系统内部异常!");
} else {
request.setAttribute("exceptionMessage", e.getMessage());// 此处待细化异常处理给显⽰???
}
try {// 跳转统⼀异常处理界⾯
request, response);
} catch (ServletException | IOException e1) {
e1.printStackTrace();
}
return null;
}
}
public void printException(Exception e) {
StringWriter sw = null;
PrintWriter pw = null;
try {
sw = new StringWriter();
pw = new PrintWriter(sw);
// 将出错的栈信息输出到printWriter中
e.printStackTrace(pw);
pw.flush();
sw.flush();
} finally {
if (sw != null) {
try {
sw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (pw != null) {
pw.close();
}
}
}
}
所有controler类继承此类实现异常统⼀处理;
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论