springboot 全局异常捕获

网友投稿 558 2022-09-11

springboot 全局异常捕获

springboot 全局异常捕获

package com.example.demo.Config;

import org.springframework.ui.Model;import org.springframework.web.bind.WebDataBinder;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.InitBinder;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.servlet.ModelAndView;

import javax.servlet.javax.servlet.with Intellij ideaUser:MingtianDate:2018/8/20Time:15:49全局异常信息*/​​@ControllerAdvice​​ //​​@ControllerAdvice​​ 作用:增强型控制器,对于控制器的全局配置放在同一个位置public class ErrorException {/**

应用到所有​​@RequestMapping​​注解方法,在其执行之前初始化数据绑定器​​@param​​​ binder*/​​@InitBinder​​public void initBinder(WebDataBinder binder) {}/**把值绑定到Model中,使全局​​@RequestMapping​​可以获取到该值​​@param​​​ model*/​​​@ModelAttribute​​​public void addAttributes(Model model,HttpServletRequest request) {model.addAttribute(“user”, request.getRemoteUser());//登陆用户}

​​//@ExceptionHandler(异常类)这个注解则表示Controller中任何一个方法发生异常,则会被注解了@ExceptionHandler的方法拦截到。​​​​// 对应的异常类执行对应的方法,如果都没有匹配到异常类,则采用近亲匹配的方式。​​​​@ExceptionHandler(value = Exception.class)​​​​public Object errorHandler(HttpServletRequest request,​​​​ HttpServletResponse response,​​​​ Exception e){​​​​ e.printStackTrace();//打印错误信息​​​​ ModelAndView mv=new ModelAndView();​​​​ mv.addObject("url",request.getRequestURL());//存放请求地址​​​​ mv.addObject("exception",e);//存放错误信息​​​​ mv.setViewName("error");//定义的错误页面​​​​ return mv;​​​​}​​​​//判断是否是ajax请求​​​​public static boolean isAjax(HttpServletRequest request){​​​​ return (request.getHeader("X-Requested-With")!=null​​​​ &&"XMLRequest".equals(request.getHeader("X-Requested-With").toString()));​​​​}​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:类的实例化过程(类的实例化过程,就是通过类创建对象的过程)
下一篇:windows配置jdk环境变量、mysql环境变量、tomcat环境变量、maven环境变量、git环境变量、node环境变量
相关文章

 发表评论

暂时没有评论,来抢沙发吧~