Skip to content

Commit

Permalink
HttpServer returns 400 Bad Request if fails to parse parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
apangin committed Sep 4, 2019
1 parent eb61d9e commit 8672aec
Showing 1 changed file with 30 additions and 2 deletions.
32 changes: 30 additions & 2 deletions src/one/nio/http/gen/RequestHandlerGenerator.java
Original file line number Diff line number Diff line change
Expand Up @@ -81,25 +81,46 @@ public RequestHandler generateFor(Method m, Object router) {

mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, className, "router", routerType);
setupArguments(mv, m);
Label invalidArgumentHandler = setupArguments(mv, m);
emitInvoke(mv, m);

if (m.getReturnType() == Response.class) {
mv.visitMethodInsn(INVOKEVIRTUAL, "one/nio/http/HttpSession", "sendResponse", "(Lone/nio/http/Response;)V");
}

mv.visitInsn(RETURN);

// catch (Exception e) {
// throw new HttpException("Invalid parameters", e);
// }
if (invalidArgumentHandler != null) {
mv.visitLabel(invalidArgumentHandler);
mv.visitVarInsn(ASTORE, 3);
mv.visitTypeInsn(NEW, "one/nio/http/HttpException");
mv.visitInsn(DUP);
mv.visitLdcInsn("Invalid parameters");
mv.visitVarInsn(ALOAD, 3);
mv.visitMethodInsn(INVOKESPECIAL, "one/nio/http/HttpException", "<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V");
mv.visitInsn(ATHROW);
}

mv.visitMaxs(0, 0);
mv.visitEnd();

cv.visitEnd();
return instantiate(cv.toByteArray(), m, router);
}

private void setupArguments(MethodVisitor mv, Method m) {
private Label setupArguments(MethodVisitor mv, Method m) {
Class[] types = m.getParameterTypes();
if (types.length == 0) {
return null;
}
Annotation[][] annotations = m.getParameterAnnotations();

Label start = new Label();
mv.visitLabel(start);

nextArgument:
for (int i = 0; i < types.length; i++) {
Class type = types[i];
Expand All @@ -120,6 +141,13 @@ private void setupArguments(MethodVisitor mv, Method m) {
throw new IllegalArgumentException("Missing @Param or @Header for argument " + i + " of " + m);
}
}

Label end = new Label();
mv.visitLabel(end);

Label invalidArgumentHandler = new Label();
mv.visitTryCatchBlock(start, end, invalidArgumentHandler, "java/lang/Exception");
return invalidArgumentHandler;
}

private void setupParam(MethodVisitor mv, Class type, Param param) {
Expand Down

0 comments on commit 8672aec

Please sign in to comment.