N
N
Newbie2016-02-28 18:35:44
Java
Newbie, 2016-02-28 18:35:44

Why is the behavior different when using ControllerAdvice?

Controller advice:

@ControllerAdvice
public class ApiControllerAdvice {
    @ExceptionHandler(ObjectNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ApiResponse notFoundError(ObjectNotFoundException exception) {
        return new ApiResponse<>(new Error(exception.getMessage()));
    }
}

controller:
@RestController
@RequestMapping("/api/library")
public class LibraryController {

    private LibraryService libraryService;

    @RequestMapping(value = "/id/{id}/**", method = RequestMethod.GET)
    public ApiResponse<Library> findOne(@PathVariable("id") long id) throws ObjectNotFoundException {
        Library library = libraryService.findOne(id);

        if (library == null) throw new ObjectNotFoundException("Library with id " + id + " not found");

        return new ApiResponse<>(library);
    }

    <...>

    @Autowired
    public void setLibraryService(LibraryService libraryService) {
        this.libraryService = libraryService;
    }
}

When requesting /api/library/id/{id}, the following Exception is thrown:
{
  "timestamp": 1456673434092,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.method.annotation.MethodArgumentTypeMismatchException",
  "message": "Failed to convert value of type [java.lang.String] to required type [long]; nested exception is java.lang.NumberFormatException: For input string: \"api\"",
  "path": "/api/library/id/3"
}

This only happens if you put the ExceptionHandler in the ControllerAdvice. If you put the ExceptionHandler in a class with the controller itself, this error does not occur. I can't figure out where the input string: \"api\" comes from.
Spring boot version 1.3.1.RELEASE.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
aol-nnov, 2016-02-28
@newbiebad

It seems to me that in order to combine @RequestMappings at the class and method levels, there should not be a leading slash in the value of the method annotation. somehow like that .
//and controller advice has nothing to do with it..

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question