简体   繁体   中英

Catching the IllegalArgumentException thrown by PropertyEditors in Spring

I have a PropertyEditor in order to translate ids into Persons , with it's setAsText (String text) as follows:

public void setAsText(String text) throws IllegalArgumentException {
    try {
        int id = Integer.parseInt(text);
        Person person = peopleService.get(id);
        this.setValue(person);
    }
    catch (NumberFormatException ex) {
        // ...
        throw new IllegalArgumentException("Not a number!: " + text);
    }
    catch (PersonNotFoundExcetion ex) {
        // ...
        throw new IllegalArgumentException("Impossible to get Person: " + text);
    }
}

And my PeopleController has a method as follows:

@RequestMapping("/getPerson")
public void ver (@RequestParam Person person, Model model) {
    model.addAttribute (person);
    // ...
}

I want to catch the IllegalArgumentException in order to show a friendly message to the user, such as "Sorry, the Person you are looking for isn't here", but I don't know where to do that...

Thanks!

General exception handling can be done in this way:

@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handleAllExceptions(Exception e) {
  return "redirect:/error.html"; /* use the correct view name */
}

More specfic you could use BindingResult

@RequestMapping(value = "/datedata", method = RequestMethod.POST)
public String create(
    @ModelAttribute("datedata") final DateData datedata,
    final BindingResult result) {

    if (result.hasErrors()) {
        return "datedata/create";
    } else {
        ...
        return "myView";
    }
 }

But I guess this works only for "Forms" (ModelAttribute)

In my humble opinion it is not a good idea to let Spring handle validaten of user input by property editors. I would strongly recommend to use the Form way: Build a command object with a STRING field an use a validator on it.

The exception ought to be caught in the Controller. It should never leak out to the view and end user.

If this is a web app, I'd recommend using the validation and binding API rather than PropertyEditor. That will allow you to return Errors that you can use to tell the UI what needs to be corrected.

Your exception handling needs work. I would not recommend catching an exception and doing nothing other than wrapping it and re-throwing. That's not handling anything or adding new information. It's actually less information as coded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM