Spring MVC 处理异常
将异常映射为HTTP状态码
映射前
public class MyException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
@Component
@RequestMapping
public class Controller {
@RequestMapping(value = "/exception", method = RequestMethod.GET)
public void exception() {
throw new MyException();
}
}
映射后
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "404")
public class MyException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
Controller 类不变
编写异常处理的方法
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Component
@RequestMapping
public class Controller {
@RequestMapping(value = "/exception", method = RequestMethod.GET)
public void exception() {
throw new RuntimeException();
}
@ExceptionHandler(RuntimeException.class)
public String handleException() {
return "error.jsp";
}
}
为控制器添加通知
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class Advice {
@ExceptionHandler(RuntimeException.class)
public String handleException() {
return "error.jsp";
}
}
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Component
@RequestMapping
public class Controller {
@RequestMapping(value = "/exception", method = RequestMethod.GET)
public void exception() {
throw new RuntimeException();
}
}
与添加映射方法同样的效果