module.exports = () => {
  return async (ctx, next) => {
    try {
      await next();
      if (ctx.state.result) {
        ctx.body = ctx.state.result;
      }
    } catch (err) {
      ctx.status = err.status || 500;
      ctx.body = {
        errors: [
          { message: err.message, stack: err.stack },
        ],
      };
    }
  };
};

@@ -11,22 +11,194 @@
 orts = (
-) =%3E %7B
+%7B debug = false %7D = %7B%7D) =%3E %7B%0A  function marshallErr (err) %7B%0A    let error = %7B message: err.message %7D;%0A    if (debug) %7B%0A      error.stack = err.stack;%0A    %7D%0A    return error;%0A  %7D%0A
 %0A  retur
@@ -252,16 +252,17 @@
 next();%0A
+%0A
       if
@@ -275,230 +275,649 @@
 stat
-e.result) %7B%0A        ctx.body = ctx.state.result;%0A      %7D%0A    %7D catch (err) %7B%0A      ctx.status = err.status %7C%7C 500;%0A      ctx.body = %7B%0A        errors: %5B%0A          %7B message: err.message, stack: err.stack %7D,%0A        %5D,%0A     
+us %3E= 400) %7B%0A        let status = ctx.status;%0A        ctx.body = ctx.body %7C%7C %7B errors: %5B %7B message: ctx.response.statusMessage %7D %5D %7D;%0A        ctx.status = status;%0A      %7D else if (ctx.state.result) %7B%0A        ctx.body = ctx.state.result;%0A      %7D%0A    %7D catch (err) %7B%0A      ctx.status = err.status %7C%7C 500;%0A      if (ctx.status %3E= 500) %7B%0A        console.error(%60Caught error with stack: $%7Berr.stack%7D%60);%0A      %7D%0A      ctx.lastError = err;%0A%0A      let errors = %5B%5D;%0A      if (err.children) %7B%0A        errors = err.children.map(childErr =%3E marshallErr(childErr));%0A      %7D else %7B%0A        errors.push(marshallErr(err));%0A      %7D%0A%0A      ctx.body = %7B errors
  %7D;%0A

Fix json middleware to handle error or non-200 http status