当前位置: 首页 > news >正文

郴州哪里做网站铜川网站建设电话

郴州哪里做网站,铜川网站建设电话,昆明网站制作公司百度推广,闵行北京网站建设由于错误在所难免#xff0c;异常处理已经成为开发工作中不可或缺的部分。在web开发中#xff0c;我们通常不希望用户看到一个写满StackTrace的错误页面#xff1b;同时#xff0c;我们希望出现错误或发生异常时#xff0c;开发运维人员可以看到详细的错误信息#xff0c…由于错误在所难免异常处理已经成为开发工作中不可或缺的部分。在web开发中我们通常不希望用户看到一个写满StackTrace的错误页面同时我们希望出现错误或发生异常时开发运维人员可以看到详细的错误信息以便进行查错和DEBUG。所以在开发过程中应重视异常处理。在进行业务逻辑开发之前就应该定义好自己的异常处理流程。1. 异常处理流程概述异常处理的对象分为两类错误的请求程序处理前就已经发生如RequestMapping中不存在该请求的URL以及其他的一些HTTP错误。程序中的错误各种异常包括Runtime异常。Springboot会统一处理第1种错误由ErrorController捕获并进行处理根据请求的Accpet字段返回错误页面或json数据。这里贴出Springboot自己的BasicErrorController实现Controllerpublic class BasicErrorController implements ErrorController { Value(${error.path:/error}) private String errorPath; private final ErrorAttributes errorAttributes; public BasicErrorController(ErrorAttributes errorAttributes) { Assert.notNull(errorAttributes, ErrorAttributes must not be null); this.errorAttributes errorAttributes; } public String getErrorPath() { return this.errorPath; } RequestMapping( value {${error.path:/error}}, produces {text/html} ) public ModelAndView errorHtml(HttpServletRequest request) { return new ModelAndView(error, this.getErrorAttributes(request, false)); } RequestMapping({${error.path:/error}}) ResponseBody public ResponseEntity error(HttpServletRequest request) { Map body this.getErrorAttributes(request, this.getTraceParameter(request)); HttpStatus status this.getStatus(request); return new ResponseEntity(body, status); } //……}也可以自己写一个ErrorController返回自定义页面。对于程序中发送的异常可以手动进行捕获。如果没有手动捕获或有所遗漏Springboot提供了ExceptionHandler(value{})对某种类型的异常统一进行处理。通常可以通过转发(forward)或重定向(redirect)方式将该异常转给自己定制的ExceptionController进行处理。ExceptionController可以根据请求类型返回错误页面或json数据。2. 自定义RuntimeException可以定制自己的Exception进行异常信息记录public abstract class BaseRuntimeException extends RuntimeException { private static final long serialVersionUID -1842796916322056555L; public BaseRuntimeException() { super(); } public BaseRuntimeException(String message) { super(message); } public BaseRuntimeException(String message, Throwable cause) { super(message, cause); } /** * 返回异常的错误码 */ public abstract Integer getErrorCode(); /** * 返回异常的描述(不带应用前缀) */ public abstract String getErrorMessage(); /** * 返回异常的日志(带应用前缀) */ public abstract String getErrorLog();}然后再Service层定义该服务模块异常信息。public class MiscServiceException extends BaseRuntimeException implements IReThrowException { private static final long serialVersionUID -1844670008823631700L; private MiscErrorCode miscErrorCode MiscErrorCode.SUCCESS; private String errorLog MiscErrorCode.SUCCESS.getDesc(); public MiscServiceException() { super(); } public MiscServiceException(String message, Throwable cause) { super(message, cause); this.errorLog message; } public MiscServiceException(String message) { super(message); this.errorLog message; } public MiscServiceException(String message, MiscErrorCode miscErrorCode) { super(message); this.miscErrorCode miscErrorCode; this.errorLog message; } /** * 返回异常的错误码. * 方便日志查看追踪. * * see BaseRuntimeException#getErrorCode() */ Override public Integer getErrorCode() { return miscErrorCode.getValue(); } /** * 返回异常的描述. * 可直接用于前端错误提示. * * see BaseRuntimeException#getErrorMessage() */ Override public String getErrorMessage() { return miscErrorCode.getDesc(); } /** * 返回异常的日志. * 用于服务器日志打印. * * see BaseRuntimeException#getErrorLog() */ Override public String getErrorLog() { return errorLog; }}在Service层生成异常对象并抛出。if (…) throw new MiscServiceException(“log message…”, MiscErrorCode.XXXERRIR);在Manager层继续向上抛出。public interface SomeService { DTO someFunc() throws MiscServiceException { //…}在Controller层捕获异常进行处理——返回相关页面。try {//…} catch (MiscServiceException e) {log.error(e.getErrorLog());return ResponseView.fail(e.getErrorCode(), e.getErrorMessage());}如此以来代码中定义的异常和错误均可以捕捉。由于BaseRuntimeException是一种RuntimeExceptionMananger层声明方法是不加throws Exception也可以通过编译。小猿建议每一个Manager的方法都加上throws Exception声明。另外BaseRuntimeException实际上也可以直接继承Exception这样编译器会强制要求对其进行异常进行处理。3. ExceptionHandler上述方案解决了一部分自定义异常。对于其他的自己未定义的Runtime Exception例如Null Pointer ExceptionSpringboot提供了ExceptionHandler用于捕获所有代码中没有主动catch的异常。通常我们该异常转发(forward)或重定向(redirect)至某个自定义的Controller进行处理。转发和重定向的效果不同在浏览器端转发的请求页面不会跳转URL不会改变重定向的请求URL会改变。重定向实际上是浏览器进行了两次请求。对于参数传递两种方式采取的方法也不同。重定向方式可以使用RedirectAttributes传递参数转发方式则将参数放置在Request的Attributes中。转发ControllerAdvicepublic class CustomExceptionHandler { /** * 将异常页转发到错误页 */ ExceptionHandler(Exception.class) public ModelAndView handleError(HttpServletRequest req, Exception ex) { log.info(Exception e : ex, ex); if (BaseRuntimeException.class.isAssignableFrom(ex.getClass())) { BaseRuntimeException e (BaseRuntimeException) ex; req.setAttribute(code, e.getErrorCode()); req.setAttribute(message, e.getErrorMessage()); } else { req.setAttribute(code, FrontCode.OTHER_ERROR.getCode()); req.setAttribute(message, FrontCode.OTHER_ERROR.getDesc()); } return new ModelAndView(forward:/exception); }}重定向/** * 将异常页使用重定向方式到错误页 * * param req * param ex * param mode * return */ExceptionHandler(Exception.class) public ModelAndView handleError(HttpServletRequest req, Exception ex ,RedirectAttributes mode) { log.info(Exception e : ex,ex); ModelAndView mav new ModelAndView(); if (BaseRuntimeException.class.isAssignableFrom(ex.getClass())) { BaseRuntimeException e (BaseRuntimeException) ex; mode.addAttribute(code,e.getErrorCode()); mode.addAttribute(message,e.getErrorMessage()); } else { mode.addAttribute(code, FrontCode.OTHER_ERROR.getCode()); mode.addAttribute(message, FrontCode.OTHER_ERROR.getDesc()); } return new ModelAndView(redirect:/exception);}4. ErrorController在下文贴出的示例中我们将异常处理的Controller也放在ErrorController中。其中errorHtml方法同于对没有经过Controller层的错误进行处理返回自定义错误页exception和exceptionHtml方法负责接收ExceptionHandler转发或重定向的异常处理流根据produces的类型是”json/application”还是“text/html”分别返回json和错误页面。Controllerpublic class CommonErrorController implements ErrorController { Autowired private UserSecurityHelper userSecurityHelper; private static final String ERROR_PATH error; private static final String EXCEPTION_PATH exception; RequestMapping(value ERROR_PATH) public ModelAndView errorHtml(HttpServletRequest request) { ModelAndView modelAndView new ModelAndView(/error/error); Object statusCode request.getAttribute(javax.servlet.error.status_code); //当请求的错误类型非404、403、402、401时返回500的错误页面 if (statusCode null || (!statusCode.equals(HttpStatus.NOT_FOUND.value()) !statusCode.equals(HttpStatus.UNAUTHORIZED.value()) !statusCode.equals(HttpStatus.PAYMENT_REQUIRED.value()) !statusCode .equals(HttpStatus.FORBIDDEN.value()))) { statusCode HttpStatus.INTERNAL_SERVER_ERROR.value(); } modelAndView.addObject(code, statusCode); modelAndView.addObject(message, 你很神找到了不存在的页面。); return modelAndView; } /* * 使用forward转发. */ RequestMapping(value EXCEPTION_PATH, produces application/json) ResponseBody public ResponseEntity exception(HttpServletRequest request) { Integer code (Integer) request.getAttribute(code); String message (String) request.getAttribute(message); return ResponseView.fail(code, message); } RequestMapping(value EXCEPTION_PATH, produces {text/html}) public ModelAndView exceptionHtml(HttpServletRequest request) { EduWebUser eduWebUser userSecurityHelper.getEduWebUser(); ModelAndView mav new ModelAndView(/error/error); mav.addObject(code, (Integer) request.getAttribute(code)); mav.addObject(message, (String) request.getAttribute(message)); mav.addObject(webUser, eduWebUser); return mav; } Override public String getErrorPath() { return ERROR_PATH; }}如果使用Redirect跳转ErrorController中接收参数的相应代码要随之改变。/*使用Redirect跳转*/RequestMapping(value EXCEPTION_PATH, produces application/json)ResponseBodypublic ResponseEntity exception(HttpServletRequest request , RequestParam(required false) String message, RequestParam(required false) Integer code) { Map body new HashMap(4); body.put(code, code); body.put(message, message); return new ResponseEntity(body, HttpStatus.OK);}RequestMapping(value EXCEPTION_PATH, produces { text/html})public ModelAndView exceptionHtml(HttpServletRequest request , RequestParam(required false) String message, RequestParam(required false) Integer code) { ModelAndView mav new ModelAndView(/error/error); EduWebUser eduWebUser userSecurityHelper.getEduWebUser(); mav.addObject(code, code); mav.addObject(message, message); mav.addObject(webUser, eduWebUser); return mav;}5. 测试我们定义了专门用于测试的Service和Controller。其中throw测试程序中代码捕获异常silent测试由ExceptionHandler捕获的异常。public interface ExceptionService { public void testThrowException() throws MiscServiceException; public void testSilentException();}Service(exceptionService)public class ExceptionServiceImpl implements ExceptionService { Override public void testThrowException() throws MiscServiceException { throw new ForumException(Log Message); } Override public void testSilentException() { throw new ForumException(Log Message); }}RestControllerRequestMapping(/exception)public class ExceptionController { Resource private ExceptionService exceptionService; RequestMapping(/throw) public ResponseEntity testThrow() { try { exceptionService.testThrowException(); return ResponseView.success(null); } catch (MiscServiceException e) { e.printStackTrace(); return ResponseView.fail(e.getErrorCode(), e.getErrorMessage()); } } RequestMapping(/silent) public ResponseEntity testSilent() { exceptionService.testSilentException(); return ResponseView.success(null); }}测试记录如下。代码主动捕获异常Springboot通过forward方式统一捕获异常Springboot通过redirect方式统一捕获异常Springboot统一捕获异常返回json对于Controller之前发生的错误和异常返回自定义页面如果对我的更新内容很感兴趣希望可以得到您的一个点赞和关注这将是对我最大的鼓励和支持感谢~不论多与少我都会坚持更新。另外私聊我【Java学习资料】可以收获互联网大厂Java面经和Java最新最全资料~帮助你早日拿到互联网大厂的offer~
http://www.sadfv.cn/news/199784/

相关文章:

  • 网站注册页面怎么做不花钱怎么做网站运营
  • 佛山个人网站建设报个计算机培训班多少钱
  • 建设网站需要先构建好模型网站建设维护工作
  • 网店装修网站博罗网站建设公司
  • 网站主页特效欣赏微信开放平台官方网站
  • wp建站优化阿里邮箱企业版入口
  • 网站规划与建设大作业答案如何把网站程序做授权网址访问
  • 网站开发公司模板定制家具品牌排行榜前十名
  • 国外互联网资讯网站张家港网站网络公司
  • 什么叫网站app网站怎么做才吸引人
  • 北京南站在几环爱站网关键词怎么挖掘
  • 杭州专业网站排名优化做游戏网站赚钱么
  • 公司网站如何做seo今天31个省新增最新消息视频
  • 建立网站的意义宇宙设计网站推荐
  • 网站做线支付平台系统多少钱凡客达人的运作模式
  • 海南省建设银行官方网站招聘温州网站制作多少钱
  • 国内it培训机构排名网站建设和seo
  • 黑龙江省建设安全协会网站外汇网站怎么做优化
  • 建瓯做网站的公司乐清网络问效平台
  • 怎么导入网站源码最新汽油价格调整最新消息
  • 电子商务网站建设考试重点高端品牌网站建设建议
  • 如何自己做的网站推广优化网站排名
  • 快速知彼网络网站建设国内优秀网站网址
  • 自己视频怎么上传网站炫彩发光字制作
  • 网站建设证据保全全国信息企业查询系统官网
  • 中铁广州建设有限公司网站驻马店 市网站建设
  • 合肥建筑网站大全成都高端网站建设哪家好
  • 长春网络建站企业网站建站费用
  • wordpress软件门户主题网站建设优化公司哪家好
  • 网站开发设计实训 报告合肥网站建设方案