全局Controller异常
1. 新建全局异常处理类
里面涉及到 @ControllerAdvice ,其实就是一个切面注解,controller层切面
package com.springboot.study.exception.handler;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
/**
* ControllerAdvice 控制层的切面
* @author like
*
*/
@ControllerAdvice
public class GlobalDefaultExceptionHandler {
@ExceptionHandler(value = Exception.class)
public void defaultErrorHandler(HttpServletRequest req, HttpServletResponse response ,Exception e) {
e.printStackTrace();
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().write(e.toString());
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
2. 新增异常方法
package com.springboot.study.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.springboot.study.bean.Demo;
/**
* Demo 控制类
* @author like
*
*/
@RestController
@RequestMapping("/demo")
public class DemoController {
@RequestMapping("/getDemo")
public Demo getDemo(){
Demo demo = new Demo();
demo.setId(1);
demo.setDemo("demo");
demo.setName("testDemo");
return demo;
}
@RequestMapping("/zero")
public int zeroException(){
return 100/0;
}
}
3. 测试
1.访问 http://localhost:8080/demo/zero
2.结果
3.在web界面已经捕获了错误,可以自定义错误错误码