package cn.edu.yale.advice;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@ControllerAdvice(annotations = RestController.class)
public class MyControllerAdvice {
@ExceptionHandler(RuntimeException.class)
public void runtimeException(RuntimeException ex, HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.write(ex.getMessage());
out.flush();
out.close();
}
}
上述配置中,只有使用@RestController注解的类发生Runtime异常时,才会进行相应的异常处理,使用@Controller注解的类发生异常时,不会进行异常处理
// Target all Controllers annotated with @RestController
@ControllerAdvice(annotations = RestController.class)
public class ExampleAdvice1 {}
// Target all Controllers within specific packages
@ControllerAdvice("org.example.controllers")
public class ExampleAdvice2 {}
// Target all Controllers assignable to specific classes
@ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class})
public class ExampleAdvice3 {}
控制器内也可以写@ExceptionHandler,它的优先级高于全局定义(就是在@ControllerAdvice中定义)的异常处理。
精准异常类型匹配的优先级更高。