springmvc異常處理
springmvc通過HandlerExceptionResolver來處理程序的異常
一般情況下使用@ExceptionHandler注解來進行標注異常處理
ExceptionHandlerExceptionResolver異常處理
- 如果出現(xiàn)異常,先是查找該Controller中用@ExceptionHandler注解定義的方法
- 如果沒有找到@ExceptionHandler注解的話,就會尋找標記了@ControllerAdvice注解的類中的@ExceptionHandler注解方法
局部異常處理
在當前Controller中處理異常(當前Controller中使用@ExceptionHandler標注的方法)
@Controller
@RequestMapping("/exception")
public class ExceptionController {
/**
* 在@Controller中所寫的@ExceptionHandler方法只能處理該Controller類中出現(xiàn)的異常,不可以處理其他Controller中出現(xiàn)的異常,此為局部異常處理
*/
@ExceptionHandler
@ResponseBody
public String exception(Exception e){
return "出現(xiàn)異常"+e.getMessage();
}
@RequestMapping("/testException")
@ResponseBody
public String testException(){
User user = null;
System.out.println(user.getId());
return "success";
}
}
全局異常處理
如果當前Controller中沒有異常處理,則會使用全局異常(使用@ControllerAdvice標注的類中的@ExceptionHandler方法)
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler
@ResponseBody
public String exception(Exception e){
return "全局捕獲: 出現(xiàn)異常"+e.getMessage();
}
}
ResponseStatusExceptionResolver異常處理
該異常處理機制是來解析@ResponseStatus來標注的異常
自定義異常
// code指定的是狀態(tài)碼,reason指定的是錯誤信息
@ResponseStatus(code = HttpStatus.BAD_REQUEST,reason = "出現(xiàn)業(yè)務(wù)異常")
public class BusinessException extends RuntimeException{
}
@RequestMapping("/testBusinessException")
@ResponseBody
public String testBusinessException(){
throw new BusinessException();
}
調(diào)用該接口就會返回到狀態(tài)碼為400的錯誤頁面
由于本身的博客百度沒有收錄,博客地址https://zhhll.com.cn