springboot-exception全局异常
@ControllerAdvice: 声明异常,标示对于控制器的全局异常捕获控制。注解有
@Controller的类都可以使用@ExceptionHandler/@InitBBinder/@ModelAttrbuite注解到方法上 。
@ExceptionHandler:全局异常,用于controller类异常处理。
@InitBBinder :用于设置WebDataBinder,WebDataBinder绑定前台请求参数到Model中。
@Controller的类都可以使用@ExceptionHandler/@InitBBinder/@ModelAttrbuite注解到方法上 。
@ExceptionHandler:全局异常,用于controller类异常处理。
@InitBBinder :用于设置WebDataBinder,WebDataBinder绑定前台请求参数到Model中。
@ModelAttrbuite :用于绑定键值对到Model中。所有注解RequestMapping的方法都可以获取到键值对。
自定义异常类
package com.example.springboot.config.exception; import org.springframework.ui.Model; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.Map; /** * 定义一个全局异常的处理类,需要使用 * * @ExceptionHandler :该注解作用对象为方法,并且在运行时有效,value()可以指定异常类。 * 由该注解注释的方法可以具有灵活的输入参数 * @ControllerAdvice: */ @ControllerAdvice public class GlobalDefaultExceptionHandler { /** * 处理 Exception 类型的异常 * * @param e * @return */ @ExceptionHandler(Exception.class) @ResponseBody public Map<String, Object> defaultExceptionHandler(Exception e) { //如果controller抛出异常,则返回500错误异常页面 Map<String, Object> map = new HashMap<String, Object>(); map.put("code", 500); map.put("msg", e.getMessage()); return map; } @ModelAttribute public void addAttrbuite(Model model) { model.addAttribute("message", "请求处理异常"); } @InitBinder public void initBinder(WebDataBinder webDataBinder) { //过滤request请求中携带的name值 webDataBinder.setDisallowedFields("name"); } }
controller类:
package com.example.springboot.config.conroller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/user") public class UserController { @RequestMapping("/hello") public String hello(){ int i = 1/0; return "hello"; } }
启动服务类:
package com.example.springboot.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; //开始定时任务配置,在标注有@Scheduled注解的定时任务才会执行。 //@EnableScheduling @SpringBootApplication public class SpringbootConfigApplication { public static void main(String[] args) { SpringApplication.run(SpringbootConfigApplication.class, args); } }
测试结果:
浏览器访问: http://localhost:8088/user/hello
当启动服务后,访问controller类,如果抛出异常,则在自定义异常类中捕获并会返回500提示。