If the problems associated with the removal can be fixed by the user, then this looks normal. If the user cannot do anything, the error code may be more correct. The only failure that I can imagine for deletion is an authorization failure, which would be 401. This can be set by adding a parameter to your "HttpServletResponse response" method. Your code will become something like:
@RequestMapping(value = "items/{id}", method = RequestMethod.DELETE) public String delete(@PathVariable("id") int itemId, Model model, HttpServletReponse response) { Item item = itemDao.get(id); // true -> can delete // false -> cannot delete, fe is FK reference somewhere boolean wasOk = itemDao.delete(item); if (!wasOk) { // will write to user which item couldn't be deleted response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); model.addAttribute("item", item); return "items/error"; } return "redirect:/items"; }
You can replace other status codes if necessary, but this is a general idea.
You can also do something like:
if (!wasOk) { throw new DataAccessException("Unable to delete item: " + item); }
And then the annotated error handler in the same class
@ExceptionHandler(DataAccessException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public String handleDataAccessException(DataAccessException ex) { // Do some stuff return "errorView"; }
Kodi
source share