異常分為兩種,一種是我們能夠通過規范代碼的書寫、條件的判斷就能夠完成的,另外一種是在運行過程中發生的,這種異常不能預期,但是我們需要處理這些異常,不能將錯誤直接拋出給用戶,通常情況下能有好的用戶體驗,該篇文章主要解決的是全局的異常處理。
public class CustomException extends Exception {
//異常信息
public String message;
public CustomException(String message) {
super(message);
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
public class HandlerException implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception exception) {
CustomException customException = null;
if (exception instanceof CustomException) {
customException = (CustomException)exception;
}else {
customException = new CustomException("未知錯誤");
}
String message = customException.getMessage(); //獲取到錯誤信息
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", message);
modelAndView.setViewName("error"); //error是邏輯視圖名,視圖解析器會將其解析為真正的物理視圖error.jsp
return modelAndView;
}
}
return_type method_name(params ...) throws Exception{
method_body;
}
<!-- 配置全局異常處理器 -->
<bean class="HandlerException類的全限定名"></bean>
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。