1、我们写一个Controller,抛出一个异常
package com.javasgj.springboot.globalexception;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController {
@RequestMapping(value="/hello")
public String hello() {
// 此处抛出异常
int a = 10 / 0;
return "Hello World!";
}
}
2、捕获全局异常类
package com.javasgj.springboot.globalexception;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public String exception() {
return "抛出异常,全局捕获";
}
}
注解:@RestControllerAdvice、@ExceptionHandler
注意:@RestControllerAdvice相当于@ControllerAdvice+@ResponseBody
能够捕获controller层抛出的异常。
3、应用启动类
package com.javasgj.springboot.globalexception;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* spring boot应用启动类
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
4、浏览器输入:http://127.0.0.1:8080/hello
输出:抛出异常,全局捕获
说明成功了!