1 将异常映射为HTTP状态码
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* @Author:musi
* @Date:2019/9/4
* @Description:
*/
@ResponseStatus(value = HttpStatus.NOT_FOUND,reason = "spittle not found")
public class SpittleNotFoundException extends RuntimeException {
}
在使用@ResponseStatus注解之后,如果控制器方法抛出SpittleNotFoundException异常的话,响应将会具有404状态码,这是因为Spittle Not Found
2 统一处理单个controller中的异常
import com.musi.exception.DuplicateSpittleException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @Author:musi
* @Date:2019/8/25
* @Description:
*/
@Controller
public class HomeController {
@RequestMapping(value="/",method = RequestMethod.GET)
public String home(){
boolean isThrowException = true;
if(isThrowException){
throw new DuplicateSpittleException();
}
return "home";
}
@RequestMapping(value="/test",method = RequestMethod.GET)
public String test(){
boolean isThrowException = true;
if(isThrowException){
throw new DuplicateSpittleException();
}
return "test";
}
@ExceptionHandler(DuplicateSpittleException.class)
public String handleDuplicateSpittle(){
return "error/duplicate";
}
}
在使用@ExceptionHandler注解之后,如果当前controller方法抛出DuplicateSpittleException异常的话,程序都会进入handleDuplicateSpittle方法,最终返回到error/duplicate页面
3 统一处理所有controller中的异常
import com.musi.exception.DuplicateSpittleException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
/**
* @Author:musi
* @Date:2019/9/4
* @Description:
*/
@ControllerAdvice
public class AppWideExceptionHandler {
@ExceptionHandler(DuplicateSpittleException.class)
public String handleDuplicateSpittle(){
return "error/duplicate";
}
}
在使用@ControllerAdvice和@ExceptionHandler注解之后,所有的controller带有RequestMapping的方法如果抛出DuplicateSpittleException异常的话,程序都会进入handleDuplicateSpittle方法,最终返回到error/duplicate页面