1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.waarp.openr66.protocol.http.restv2.resthandlers;
22
23 import io.cdap.http.ExceptionHandler;
24 import io.cdap.http.HttpResponder;
25 import io.netty.handler.codec.http.DefaultHttpHeaders;
26 import io.netty.handler.codec.http.HttpRequest;
27 import org.waarp.common.logging.WaarpLogger;
28 import org.waarp.common.logging.WaarpLoggerFactory;
29 import org.waarp.openr66.protocol.http.restv2.errors.RestErrorException;
30 import org.waarp.openr66.protocol.http.restv2.utils.JsonUtils;
31 import org.waarp.openr66.protocol.http.restv2.utils.RestUtils;
32
33 import javax.ws.rs.InternalServerErrorException;
34 import javax.ws.rs.NotSupportedException;
35 import java.util.Locale;
36
37 import static io.netty.handler.codec.http.HttpResponseStatus.*;
38 import static javax.ws.rs.core.HttpHeaders.*;
39
40
41
42
43
44 public class RestExceptionHandler extends ExceptionHandler {
45
46
47
48
49 private static final WaarpLogger logger =
50 WaarpLoggerFactory.getLogger(RestExceptionHandler.class);
51
52
53
54
55
56
57
58
59
60 @Override
61 public void handle(final Throwable t, final HttpRequest request,
62 final HttpResponder responder) {
63 if (t instanceof RestErrorException) {
64 final RestErrorException userErrors = (RestErrorException) t;
65 try {
66 final Locale lang = RestUtils.getLocale(request);
67 final String errorText =
68 JsonUtils.nodeToString(userErrors.makeNode(lang));
69 responder.sendJson(BAD_REQUEST, errorText);
70 } catch (final InternalServerErrorException e) {
71 logger.error(e);
72 responder.sendStatus(INTERNAL_SERVER_ERROR);
73 }
74 } else if (t instanceof NotSupportedException) {
75 final DefaultHttpHeaders headers = new DefaultHttpHeaders();
76 headers.add(ACCEPT, t.getMessage());
77 responder.sendStatus(UNSUPPORTED_MEDIA_TYPE, headers);
78 } else {
79 logger.error(t);
80 responder.sendStatus(INTERNAL_SERVER_ERROR);
81 }
82 }
83 }