Home > OS >  custom Exceptions while working on spring boot web
custom Exceptions while working on spring boot web

Time:10-13

I have a Controller which is implementing ErrorController

which handles any error that occurs in my spring project, below is the code.

@Controller
public class CustomErrorController implements ErrorController {
    @RequestMapping("/error")
    public void springWebErrors() {
       return "springWebErrorPage"
    }
}

also, I have mentioned

server.error.path=/error

but I am stuck where sometimes data might be not as per needs, so I want to give my customized messages,

are there any ideas on how to achieve it? (thanks)

CodePudding user response:

As far as I understood your concern,

You want your application to handle errors/ exceptions when user sends invalid data, I have applied same thing in my code using custom Exceptions, ControllerAdvice & Exception Handler,

please check the below code, which might be useful.

@ControllerAdvice
public class ExceptionController {

    @ExceptionHandler(value = PageNotFoundException.class)
    public String pageNotFoundException(PageNotFoundException exception){
        return "error/404";
    }

    @ExceptionHandler(value = AuthFailedException.class)
    public String authFailedException(AuthFailedException exception){
        return "error/401";
    }

    @ExceptionHandler(value = ServerException.class)
    public String serverException(ServerException exception){
        return "error/500";
    }
}

Explanation: @ControllerAdvice & @ExceptionHandler is global error controller, you can visit the documentation here

@Controller
public class CustomizedErrorController implements ErrorController {
    @RequestMapping("/error")
    public void handleError(HttpServletRequest request) {
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        if (status != null) {
            int statusCode = Integer.parseInt(status.toString());
            if(statusCode == HttpStatus.NOT_FOUND.value()) {
                throw new PageNotFoundException();
            }
            else if(statusCode == HttpStatus.UNAUTHORIZED.value()) {
                throw new AuthFailedException();
            }
            else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                throw new ServerException();
            }
        }
        else{
            throw new OtherException();
        }
    }
}

You can also throw your custom exception from your implementation or controller file.

I hope, it helps

  • Related