您好,登錄后才能下訂單哦!
在Spring MVC應用中處理異常通常可以通過以下幾種方式實現:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ModelAndView handleException(Exception ex) {
ModelAndView mav = new ModelAndView();
mav.addObject("message", "An error occurred: " + ex.getMessage());
mav.setViewName("errorPage");
return mav;
}
}
@Controller
public class MyController {
@RequestMapping("/handleException")
public String handleException() {
throw new CustomException("Something went wrong");
}
@ExceptionHandler(CustomException.class)
public ModelAndView handleCustomException(CustomException ex) {
ModelAndView mav = new ModelAndView();
mav.addObject("message", "An error occurred: " + ex.getMessage());
mav.setViewName("errorPage");
return mav;
}
}
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<Object> handleResourceNotFoundException(ResourceNotFoundException ex) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("message", "Resource not found");
body.put("timestamp", LocalDateTime.now());
return new ResponseEntity<>(body, HttpStatus.NOT_FOUND);
}
}
這些是處理異常的一些常見方法,在實際應用中可以根據具體需求選擇合適的方式來處理異常。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。