0

i would like to implement an exception handler for restful api if the uri is not matched.
For example:
url is localhost:8080\test\generateNumber will return {"response_code":"200"}

and

if the url is wrong for example:
localhost:8080\test\generateNumber2 will return {"response_code":"404","message":"uri not found"}

i have no idea on how to do it. Can someone help?

Tora
  • 11
  • 3

1 Answers1

0

I presume you're using Spring?

In that case you can use @ExceptionHandler like this:

@RestController
public class Example1Controller {

    @GetMapping(value = "/testExceptionHandler", produces = APPLICATION_JSON_VALUE)
    public Response testExceptionHandler(@RequestParam(required = false, defaultValue = "false") boolean exception)
            throws BusinessException {
        if (exception) {
            throw new BusinessException("BusinessException in testExceptionHandler");
        }
        return new Response("OK");
    }

    @ExceptionHandler(BusinessException.class)
    public Response handleException(BusinessException e) {
        return new Response(e.getMessage());
    }

}

And get a message in response.

More - in this manual.

swapper9
  • 33
  • 1
  • 8