Şu satırı dahil ederiz
import org.springframework.web.servlet.HandlerExceptionResolver;
Exception döndürmek için 3 yöntem var
- @ControllerAdvice + @ExceptionHandler : Global Exception handling yapar- HandlerExceptionResolver- ResponseStatusException
Bu sınıf direkt ResponseStatusException fırlatmaktan daha iyi, çünkü merkezi bir noktadan Exception'lar kontrol edilebilir. Bu sınıf yerine @ControllerAdvice veya @ExceptionHandler kullanılabilir.
Filtrelerden Kullanmak
Şöyle yaparız
public class AuthorizationFilter extends BasicAuthenticationFilter { private final HandlerExceptionResolver exceptionResolver; public AuthorizationFilter(AuthenticationManager authenticationManager, HandlerExceptionResolver exceptionResolver) { super(authenticationManager); this.exceptionResolver = exceptionResolver; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { try { ... } catch (ExpiredJwtException e) { exceptionResolver.resolveException(request, response, null, e); } } }
Örnek
Şöyle yaparız
@Component class RestResponseStatusExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) { ModelAndView model = new ModelAndView(); model.setView(new MappingJackson2JsonView()); model.addObject("exception", exception.getMessage()); return model; } } @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void configureHandlerExceptionResolvers( List<HandlerExceptionResolver> resolvers) { resolvers.add(0, new RestResponseStatusExceptionResolver()); } }
HTTP cevabı şöyledir
{ "serviceDownTimeException": { "cause": null, "stackTrace": [], "localizedMessage": "1-2 AM is service downtime!", "message": "1-2 AM is service downtime!", "suppressed": [] } }