简体   繁体   中英

How to keep exception Message in modelmapper converter

I am using ModelMapper and there I define some PostConverters like:

    modelMapper
            .createTypeMap(TestDTO.class, Test.class)
            .setPostConverter(converter -> {
                Test dest = converter.getDestination();
                TestDTO source = converter.getSource();
                if (source.getDependency() != null) {
                    Dependency dependency = dependencyRepository
                            .findById(source.getDependency().getId())
                            .orElseThrow(() -> new BadRequestException("Invalid Dependency"));
                    dest.setDependency(dependency);
                }
                return dest;
            });

The problem with that code is that, if I put an invalid id for the dependency, then I receive a response payload like:

{
    "timestamp": "2018-09-18T13:51:05.203+0200",
    "status": 400,
    "error": "Bad Request",
    "message": "ModelMapper mapping errors:\n\n1) Converter ....",
    "path": "/api/test"
}

But I want that in the error message I get Invalid Dependency . Any Idea how to do it?

Here is the Definition of the BadRequestException:

@ResponseStatus(HttpStatus.BAD_REQUEST)
public class BadRequestException extends RunTimeException {

    public BadRequestException() {
        super("Bad Request");
    }

    public BadRequestException(String message) {
        super(message);
    }

    public BadRequestException(String pattern, Object... parameters) {
        super(pattern, parameters);
    }
}

The fault seems to be in your exception handling with the annotation, see here:
https://docs.spring.io/spring/docs/4.2.4.RELEASE/javadoc-api/org/springframework/web/bind/annotation/ResponseStatus.html

It says:
"Warning: when using this annotation on an exception class, or when setting the reason attribute of this annotation, the HttpServletResponse.sendError method will be used." It seems like the method does not use your exception message by default. So you could either try defining a 'hardcoded' message and give a concrete string with

 @ResponseStatus(value = HttpStatus.BadRequest, reason = "Invalid Dependency")

Or do it in a kind of this way:

public class BadRequestException extends RunTimeException {

public BadRequestException() {
    super("Bad Request");
}

public BadRequestException(String message) {
    super(message);
}

public BadRequestException(String pattern, Object... parameters) {
    super(pattern, parameters);
}

}

@ControllerAdvice
public class CustomExceptionResolver {

    @ExceptionHandler(BadRequestException.class)
    public ResponseEntity<Error> resolveAndSendException(BadRequestException e) throws IOException {
        return new ResponseEntity<Error>(e, HttpStatus.BadRequest); 
    }
}

I would prefer the first one, with a slight change:
Introduce a new class called InvalidDependencyException and apply the first example to this class, so you have your message and still can use the integrated messages for any other bad request. (Throw it of course in your stream-part)

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