1 package common.http.error;
2
3 import usecase.auth.AuthenticationRequiredException;
4 import usecase.auth.AuthorizationException;
5 import usecase.auth.BannedUserException;
6
7 import javax.servlet.FilterChain;
8 import javax.servlet.ServletException;
9 import javax.servlet.annotation.WebFilter;
10 import javax.servlet.http.HttpFilter;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 import javax.validation.ConstraintViolation;
14 import javax.validation.ConstraintViolationException;
15 import java.io.IOException;
16 import java.time.format.DateTimeFormatter;
17 import java.util.stream.Collectors;
18
19 import static javax.servlet.http.HttpServletResponse.*;
20
21 @WebFilter("*")
22 class FallbackExceptionHandlerFilter extends HttpFilter {
23
24
25 @Override
26 protected void doFilter(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException {
27 try{
28 chain.doFilter(req, resp);
29 } catch (IllegalArgumentException e) {
30 resp.sendError(SC_BAD_REQUEST, e.getMessage());
31 } catch (ConstraintViolationException e) {
32 String messages = e.getConstraintViolations().stream()
33 .map(ConstraintViolation::getMessage).collect(Collectors.joining("\n"));
34 resp.sendError(SC_BAD_REQUEST, messages);
35 } catch (AuthenticationRequiredException e) {
36 resp.sendError(SC_UNAUTHORIZED, e.getMessage());
37 } catch (BannedUserException e){
38 if (e.getDuration() != null){
39 String end = DateTimeFormatter.ISO_INSTANT.format(e.getDuration());
40 resp.sendError(SC_FORBIDDEN, "Sei bannato fino a " + end);
41 } else {
42 resp.sendError(SC_FORBIDDEN, e.getMessage());
43 }
44 } catch (AuthorizationException e) {
45 resp.sendError(SC_FORBIDDEN, e.getMessage());
46 }
47 }
48 }