File: JsonErrorReportValve.java

package info (click to toggle)
tomcat10 10.1.52-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 47,900 kB
  • sloc: java: 375,756; xml: 59,410; jsp: 4,741; sh: 1,381; perl: 324; makefile: 25; ansic: 14
file content (148 lines) | stat: -rw-r--r-- 5,811 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.catalina.valves;

import java.io.IOException;
import java.io.Writer;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.coyote.ActionCode;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.json.JSONFilter;
import org.apache.tomcat.util.res.StringManager;

/**
 * Implementation of a Valve that outputs error JSON. This Valve should be attached at the Host level, although it will
 * work if attached to a Context.
 */
public class JsonErrorReportValve extends ErrorReportValve {

    public JsonErrorReportValve() {
        super();
    }

    @Override
    protected void report(Request request, Response response, Throwable throwable) {

        int statusCode = response.getStatus();

        // Do nothing on a 1xx, 2xx and 3xx status
        // Do nothing if anything has been written already
        // Do nothing if the response hasn't been explicitly marked as in error
        // and that error has not been reported.
        if (statusCode < 400 || response.getContentWritten() > 0 || !response.setErrorReported()) {
            return;
        }

        // If an error has occurred that prevents further I/O, don't waste time
        // producing an error report that will never be read
        AtomicBoolean result = new AtomicBoolean(false);
        response.getCoyoteResponse().action(ActionCode.IS_IO_ALLOWED, result);
        if (!result.get()) {
            return;
        }

        StringManager smClient = StringManager.getManager(Constants.Package, request.getLocales());
        response.setLocale(smClient.getLocale());
        String type;
        if (throwable != null) {
            type = smClient.getString("errorReportValve.exceptionReport");
        } else {
            type = smClient.getString("errorReportValve.statusReport");
        }
        String message = response.getMessage();
        if (message == null && throwable != null) {
            message = throwable.getMessage();
        }
        if (message == null) {
            message = "";
        }
        String description = smClient.getString("http." + statusCode + ".desc");
        if (description == null) {
            if (message.isEmpty()) {
                return;
            } else {
                description = smClient.getString("errorReportValve.noDescription");
            }
        }
        StringBuilder sb = new StringBuilder();
        sb.append("{\n  \"type\": \"").append(JSONFilter.escape(type)).append("\",\n");
        sb.append("  \"status\": ").append(statusCode).append(",\n");
        sb.append("  \"message\": \"").append(JSONFilter.escape(message)).append("\",\n");
        sb.append("  \"description\": \"").append(JSONFilter.escape(description));

        if (throwable != null) {
            sb.append("\",\n");

            // Stack trace
            sb.append("  \"throwable\": [");
            boolean first = true;
            do {
                if (!first) {
                    sb.append(',');
                } else {
                    first = false;
                }
                sb.append('\"').append(JSONFilter.escape(throwable.toString())).append('\"');

                StackTraceElement[] elements = throwable.getStackTrace();
                int pos = elements.length;
                for (int i = elements.length - 1; i >= 0; i--) {
                    if ((elements[i].getClassName().startsWith("org.apache.catalina.core.ApplicationFilterChain")) &&
                            (elements[i].getMethodName().equals("internalDoFilter"))) {
                        pos = i;
                        break;
                    }
                }
                for (int i = 0; i < pos; i++) {
                    if (!(elements[i].getClassName().startsWith("org.apache.catalina.core."))) {
                        sb.append(',').append('\"').append(' ').append(JSONFilter.escape(elements[i].toString()))
                                .append('\"');
                    }
                }

                throwable = throwable.getCause();
            } while (throwable != null);
            sb.append("]\n}");

        } else {
            sb.append("\"\n}");
        }

        try {
            try {
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
                if (container.getLogger().isDebugEnabled()) {
                    container.getLogger().debug(sm.getString("errorReportValve.contentTypeFail"), t);
                }
            }
            Writer writer = response.getReporter();
            if (writer != null) {
                writer.write(sb.toString());
                response.finishResponse();
            }
        } catch (IOException | IllegalStateException e) {
            // Ignore
        }
    }

}