comparison src/goodjava/webserver/Connection.java @ 1750:c7b3c327248a

webserver error handling
author Franklin Schmidt <fschmidt@gmail.com>
date Tue, 10 Jan 2023 22:42:47 -0700
parents 9713f7fd50b3
children b4fa42c1e999
comparison
equal deleted inserted replaced
1749:d1e7564a9ce5 1750:c7b3c327248a
70 String lenStr = (String)request.headers.get("content-length"); 70 String lenStr = (String)request.headers.get("content-length");
71 if( lenStr != null ) { 71 if( lenStr != null ) {
72 int len = Integer.parseInt(lenStr); 72 int len = Integer.parseInt(lenStr);
73 byte[] body = new byte[len]; 73 byte[] body = new byte[len];
74 size -= endOfHeader; 74 size -= endOfHeader;
75 System.arraycopy(a,endOfHeader,body,0,size); 75 try {
76 System.arraycopy(a,endOfHeader,body,0,size);
77 } catch(ArrayIndexOutOfBoundsException e) {
78 throw new WrappedRuntimeException(e);
79 }
76 while( size < len ) { 80 while( size < len ) {
77 int n = in.read(body,size,len-size); 81 int n = in.read(body,size,len-size);
78 if( n == -1 ) { 82 if( n == -1 ) {
79 throw new IOException("unexpected end of input at "+size); 83 throw new IOException("unexpected end of input at "+size);
80 } 84 }
111 return; 115 return;
112 } 116 }
113 117
114 response = server.handler.handle(request); 118 response = server.handler.handle(request);
115 } catch(ParseException e) { 119 } catch(ParseException e) {
116 logger.warn("parse error\n"+request.rawHead.trim()+"\n",e); 120 logger.warn("parse error\n"+rawHead.trim()+"\n",e);
117 String msg = e.toString(); 121 String msg = e.toString();
118 if( contentType != null ) 122 if( contentType != null )
119 msg = "invalid content for content-type " + contentType + "\n" + msg; 123 msg = "invalid content for content-type " + contentType + "\n" + msg;
120 response = Response.errorResponse(Status.BAD_REQUEST,msg); 124 response = Response.errorResponse(Status.BAD_REQUEST,msg);
121 } 125 }
128 IoUtils.copyAll(response.body.content,out); 132 IoUtils.copyAll(response.body.content,out);
129 out.close(); 133 out.close();
130 socket.close(); 134 socket.close();
131 } catch(IOException e) { 135 } catch(IOException e) {
132 logger.info(rawHead.trim()+"\n",e); 136 logger.info(rawHead.trim()+"\n",e);
137 } catch(WrappedRuntimeException wrapped) {
138 RuntimeException e = (RuntimeException)wrapped.getCause();
139 logger.info(rawHead.trim()+"\n",e);
140 throw e;
133 } catch(RuntimeException e) { 141 } catch(RuntimeException e) {
134 logger.error(rawHead.trim()+"\n",e); 142 logger.error(rawHead.trim()+"\n",e);
135 throw e; 143 throw e;
136 } 144 }
137 } 145 }
138 146
147 private static final class WrappedRuntimeException extends Exception {
148 WrappedRuntimeException(RuntimeException e) {
149 super(e);
150 }
151 }
139 } 152 }