简体   繁体   中英

Custom Exception throw in Spring Boot Application

I Want to create some custom exception in my spring boot application using @ControllerAdvice and @ExceptionHandler but I can get exception details as a json

I tried every thing could not find the solution. ErrorDetails is a class where i used setter and getter and StringNotFoundException is class which extends Exception

    @ControllerAdvice()
    public class RestExceptionHandler {

    @Autowired
    Environment environment;

    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    @ExceptionHandler(StringNotFoundException.class)
    @ResponseBody
    public ErrorDetails handleNotFoundException(StringNotFoundException ex, HttpServletRequest request) {

        ErrorDetails ed = new ErrorDetails();
        ed.setErrorCode("10000");
        ed.setErrorMessage(ex.getMessage());
        ed.setErrorDescription("Try");
        ed.setPort(environment.getProperty("local.server.port"));
        ed.setUrl(request.getRequestURI().toString());
        System.out.println(ed + "****************");
        return ed;}}

In controller I using this:

if (companyList.isEmpty()) {
throw new StringNotFoundException();
            }

Exception details shows on console but i could not get json format

com.ffi.financialcompany.exception.StringNotFoundException

Try making RestExceptionHandler extends ResponseEntityExceptionHandler.

ResponseEntityExceptionHandler is a class used by Spring framework to throw Exceptions. I think you should extend that class in order to work this out.

    @ControllerAdvice()
    public class RestExceptionHandler extends  ResponseEntityExceptionHandler {
    ....

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