如题,本篇我们介绍下springboot中统一异常500处理,以及错误页404处理。

一、统一异常处理(500)

主要针对于服务器出现500异常的情况,返回自定义的500页面到用户浏览器,或者输出错误json数据到用户浏览器。

如果ex是业务层抛出的自定义异常则或取自定义异常的自定义状态码和自定义消息+错误堆栈信息;如果ex不是自定义异常,则获取ex的错误堆栈信息。

MvcExceptionResolver.java

package com.tingcream.springWeb.mvc;import java.io.IOException;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;import com.alibaba.fastjson.JSON;
import com.tingcream.springWeb.exception.ServiceCustomException;
import com.tingcream.springWeb.util.AjaxUtil;/*** mvc异常处理器* @author jelly**/
@Component
public class MvcExceptionResolver  implements HandlerExceptionResolver{private   Logger logger = Logger.getLogger(MvcExceptionResolver.class);@Overridepublic ModelAndView resolveException(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex) {response.setContentType("text/html;charset=UTF-8");response.setCharacterEncoding("UTF-8");try {String errorMsg="";boolean isAjax= "1".equals(request.getParameter("isAjax"));//ex 为业务层抛出的自定义异常if(ex instanceof ServiceCustomException){ServiceCustomException customEx=    (ServiceCustomException)ex;errorMsg ="customStatus:"+customEx.getCustomStatus() +",customMessage:"+customEx.getCustomMessage()+"\r\n"+ ExceptionUtils.getStackTrace(customEx);logger.error(errorMsg);}else{//ex为非自定义异常,则errorMsg=ExceptionUtils.getStackTrace(ex);logger.error(errorMsg);}if(isAjax){response.setContentType("application/json;charset=UTF-8");response.getWriter().write(JSON.toJSONString(AjaxUtil.messageMap(500, errorMsg)));return new   ModelAndView();}else{//否则,  输出错误信息到自定义的500.jsp页面ModelAndView mv = new ModelAndView("/error/500.jsp");mv.addObject("errorMsg", errorMsg);return mv ;}} catch (IOException e) {logger.error(ExceptionUtils.getStackTrace(e));}return new   ModelAndView();}}

ServiceCustomException.java

package com.tingcream.springWeb.exception;/*** 业务自定义异常* @author jelly**/
public class ServiceCustomException  extends RuntimeException{private  Integer customStatus;private String customMessage;private static final long serialVersionUID = 1L;public ServiceCustomException() {super();}public ServiceCustomException(Integer customStatus ,String customMessage) {this.customStatus=customStatus;this.customMessage=customMessage;}public ServiceCustomException(Integer customStatus ,String customMessage,Throwable cause) {super(cause);this.customStatus=customStatus;this.customMessage=customMessage;}public Integer getCustomStatus() {return customStatus;}public void setCustomStatus(Integer customStatus) {this.customStatus = customStatus;}public String getCustomMessage() {return customMessage;}public void setCustomMessage(String customMessage) {this.customMessage = customMessage;}}

500.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!DOCTYPE html>
<html><head><base href="<%=basePath%>"><title>500</title></head><body><h3>糟糕! 服务器出错啦~~(>_<)~~</h3><div>异常信息如下:<br/>${errorMsg }</div></body>
</html>

我们在controller方法中模拟抛出一个异常

@RequestMapping("/")public  String home(HttpServletRequest request, HttpServletRequest response){int a =3/0;//不能被0除异常request.setAttribute("message", "早上好,朋友们!");return "/home.jsp";
}

AjaxUtil.java

package com.tingcream.springWeb.util;import java.util.HashMap;
import java.util.Map;public class AjaxUtil {//得到一个mappublic static Map<String,Object> getMap(){return new HashMap<String,Object>();}//返回json数据 状态public static Map<String,Object> messageMap(int status){Map<String,Object>  map=new HashMap<String,Object>();map.put("status", status);return map; }//返回json数据 状态、消息public static Map<String,Object> messageMap(int status,String message){Map<String,Object>  map=new HashMap<String,Object>();map.put("status", status);map.put("message", message);return map;}//返回json数据 状态、消息 和一个参数public  static Map<String,Object> messageMap(int status,String message,String paramName,Object paramValue){Map<String,Object>  map=new HashMap<String,Object>();map.put("status", status);map.put("message", message);map.put(paramName, paramValue);return map;}//返回json数据 状态、消息 和多个参数public static Map<String,Object> messageMap(int status,String message,String[] paramNames,Object[] paramValues){Map<String,Object>  map=new HashMap<String,Object>();map.put("status", status);map.put("message", message);if(paramNames!=null&&paramNames.length>0){for(int i=0;i<paramNames.length;i++){map.put(paramNames[i], paramValues[i]);}}return map;}
}

用浏览器访问首页,发现报错了,进入了500.jsp页面 。

ok,说明500异常处理配置成功 !!

二、错误页处理(404)

主要针对404请求的情况,如用户在浏览器中随意地输入了一个不存在的路径。

ErrorPageController.java

package com.tingcream.springWeb.mvc;import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;/*** 错误页(404) 处理* @author jelly**/@Controller
public class ErrorPageController implements ErrorController {private static final String ERROR_PATH = "/error";@RequestMapping(ERROR_PATH)public String error(){return "/error/404.jsp";}@Overridepublic String getErrorPath() {return ERROR_PATH;}
}

404.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!DOCTYPE html >
<html><head><base href="<%=basePath%>"><title>404</title></head><body><h2>404</h2><h3>抱歉,您访问的页面好像被火星汪叼走了!</h3></body>
</html>

启动服务器,随便访问一个不存在的路径。。

ok,说明错误页(404) 配置成功 !!

springboot(九)--统一异常处理(500)、错误页处理(404)相关推荐

  1. html500错误原因1003无标题,web工程中404/500错误页面配置+404页面模板

    [实例简介] web工程中404/500错误页面配置+404页面模板 [实例截图] [核心代码] 247959a9-c3ea-4360-8e57-105d680b29f0 ├── 404页面模板 │  ...

  2. 【转载】ASP.NET自定义404和500错误页面

    在ASP.NET网站项目实际上线运行的过程中,有时候在运行环境下会出现400错误或者500错误,这些错误默认的页面都不友好,比较简单单调,其实我们可以自行设置这些错误所对应的页面,让这些错误跳转到我们 ...

  3. 服务器 1 500错误信息,什么是500错误

    什么是500错误[编辑] 概述 500错误页面,则说明了内部服务器无法解析ASP代码.但有时候它能打开静态页面问题.如果静态页面没有问题,则是具体问题具体分析. 一.查看错误信息 1."服务 ...

  4. 手机服务器响应出错 错误码500,手机服务器500错误原因

    我们浏览网页的时候会遇到这样或者那样的错误,下面学习啦小编为大家整理了关于服务器错误500手机的内容,欢迎参阅. 服务器错误500 其实"服务器错误500"只是一个统称,所有内部服 ...

  5. Springboot关于错误页面处理和统一异常处理

    01.概述 在项目访问的时候我们经常会发生错误或者页面找不到,比如:资源找不到404,服务器500错误,默认情况下springboot的处理机制都是去跳转内部的错误地址:/error 和与之对应的一个 ...

  6. Springboot对web应用的统一异常处理

    我们在做Web应用的时候,请求处理过程中发生错误是非常常见的情况.Spring Boot提供了一个默认的映射:/error,当处理中抛出异常之后,会转到该请求中处理,并且该请求有一个全局的错误页面用来 ...

  7. 配置springboot在访问404时自定义返回结果以及统一异常处理

    在搭建项目框架的时候用的是springboot,想统一处理异常,但是发现404的错误总是捕捉不到,总是返回的是springBoot自带的错误结果信息. 如下是springBoot自带的错误结果信息: ...

  8. SpringBoot 错误页面使用、自定义错误页、自定义异常、自定义异常解析器

    在SpringBoot使用错误页面非常的简单 一. 错误页面使用 二. 自定义错误页 三.自定义异常 四.自定义异常解析器 一. 错误页面使用 只需要在templates里创建一个error文件夹,然 ...

  9. springboot整合之统一异常处理

    特别说明:本次项目整合基于idea进行的,如果使用Eclipse可能操作会略有不同,不过总的来说不影响. springboot整合之如何选择版本及项目搭建 springboot整合之版本号统一管理  ...

最新文章

  1. ELK 处理 Spring Boot 日志,妙!
  2. jwt 私钥_JSON Web Token (JWT)生成Token及解密实战。
  3. 第五周项目二-游戏中的角色类(2)
  4. linux命令大全增删改查,crudini命令
  5. python 网络爬虫介绍
  6. 搜索引擎其实是一个读库
  7. [css] 如何做图片预览,如何放大一个图片?
  8. Android编译自定义sdk,java – 使用自定义android.bluetooth.而不是在android studio中默认的sdk android.jar中存在一个...
  9. Python实现随机生成10以内的加法
  10. 前端—每天5道面试题(6)
  11. 趣谈新春年俗:古代过年为啥要贴门神像?
  12. 提高Office2010等高版的启动速度文章链接收集-Office2010打开慢速度怎么办?
  13. pythoncsv格式清洗与转换_Python中 CSV格式清洗与转换的实例代码
  14. tooltips被遮盖
  15. 2022下半年软件设计师中级考试通过
  16. 对SLAM和自动驾驶定位的思考,最新自动驾驶视觉SLAM方法综述!
  17. Maven系列之使用阿里云仓库
  18. C语言写一个函数,可以逆序一个字符串的内容。
  19. 程序员的简历应该这么写!!
  20. 《你不知道的JavaScript(上卷)》——[美]凯尔辛普森

热门文章

  1. Web测试方法与技术之CSS讲解
  2. Win8下装XP双系统
  3. 微信小程序医院门诊体检预约信息管理系统SSM-JAVA【数据库设计、论文、源码、开题报告】
  4. JointJS入门实例01-在JOINTJS元素中使用HTML
  5. Class类是什么?
  6. 各种SQL子查询实例
  7. Spark学习-DAY4
  8. 将同一文件夹内的所有txt文件内容合并到一个txt中
  9. MessageBox.Show()的用法
  10. centos 8 编译安装hyperscan