简体   繁体   中英

Get to the root validation cause

I have a RestController that validates its input:

class Item {}
class ItemHolder {
  Item item;
}

@RestController
public class ItemRestController {
    @GetMapping
    public String get(@Valid ItemHolder itemHolder) { }
}

I have a parameter converter that throws a custom exception with an important message:

class CannotConvertException extends RuntimeException {}

class ItemConverter implements Converter<String, Item> {
  @Override
  public Item convert(String value) {
    throw new CannotConvertException("Important failure message: " + value);
  }
}

I also have an exception handler:

@ControllerAdvice
class ResponseExceptionHandler extends ResponseEntityExceptionHandler {
  @Override
  protected ResponseEntity<Object> handleBindException(
            BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {

        // How to get only the message from CannotConvertException here?
    }

Inside handleBindException , the message (ie ex.getMessage() ) I get is something like:

org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'itemHolder' on field 'item': rejected value [very bad value]; codes [typeMismatch.itemHolder.item,typeMismatch.item,typeMismatch.com.example.Item,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [itemHolder.item,item]; arguments []; default message [item]]; default message [Failed to convert value of type 'java.lang.String[]' to required type 'com.example.Item'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [com.example.Item] for value 'very bad value'; nested exception is com.example.CannotConvertException: Important failure message: very bad value]

Without resorting to hacks such as string parsing or reflection, how would I go around making sure that the exception handler can get to the Important failure message: very bad value part only, without all the noise before it?

I'm fine changing the converter if that is a better alternative.

Instead of the custom exception you have in your convertor try to throw MethodArgumentTypeMismatchException and in the advice add a new method to handle these types of exception.

This should solve your problem!

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