77import org .springframework .web .bind .annotation .ControllerAdvice ;
88import org .springframework .web .bind .annotation .ExceptionHandler ;
99import org .springframework .web .servlet .ModelAndView ;
10+ import org .springframework .web .servlet .NoHandlerFoundException ;
1011import ru .javawebinar .topjava .AuthorizedUser ;
1112import ru .javawebinar .topjava .util .ValidationUtil ;
1213import ru .javawebinar .topjava .util .exception .ErrorType ;
@@ -24,15 +25,23 @@ public GlobalExceptionHandler(MessageSourceAccessor messageSourceAccessor) {
2425 this .messageSourceAccessor = messageSourceAccessor ;
2526 }
2627
28+ @ ExceptionHandler (NoHandlerFoundException .class )
29+ public ModelAndView wrongRequest (HttpServletRequest req , NoHandlerFoundException e ) throws Exception {
30+ return logAndGetExceptionView (req , e , false , ErrorType .WRONG_REQUEST , HttpStatus .BAD_REQUEST );
31+ }
32+
2733 @ ExceptionHandler (Exception .class )
2834 public ModelAndView defaultErrorHandler (HttpServletRequest req , Exception e ) throws Exception {
2935 log .error ("Exception at request " + req .getRequestURL (), e );
30- Throwable rootCause = ValidationUtil .logAndGetRootCause (log , req , e , true , ErrorType .APP_ERROR );
36+ return logAndGetExceptionView (req , e , true , ErrorType .APP_ERROR , HttpStatus .INTERNAL_SERVER_ERROR );
37+ }
38+
39+ private ModelAndView logAndGetExceptionView (HttpServletRequest req , Exception e , boolean logException , ErrorType errorType , HttpStatus httpStatus ) {
40+ Throwable rootCause = ValidationUtil .logAndGetRootCause (log , req , e , logException , errorType );
3141
32- HttpStatus httpStatus = HttpStatus .INTERNAL_SERVER_ERROR ;
3342 ModelAndView mav = new ModelAndView ("exception" ,
3443 Map .of ("exception" , rootCause , "message" , ValidationUtil .getMessage (rootCause ),
35- "typeMessage" , messageSourceAccessor .getMessage (ErrorType . APP_ERROR .getErrorCode ()),
44+ "typeMessage" , messageSourceAccessor .getMessage (errorType .getErrorCode ()),
3645 "status" , httpStatus ));
3746 mav .setStatus (httpStatus );
3847
0 commit comments