# "web.onError sees every error as Error": a handler throws a StockError,# web answers 500, logs the struct to standard error and hands the hook an# Error with the same kind and message. The demo then asks itself for# /buy/T-42 on a loopback port.use io;
use httpd;
usetask;
use time;
import"web.j"as web;
import"http.j"as http;
defstruct StockError { kind asstring, message asstring, sku asstring };
funcbuy(ctx asweb.Context) {
def sku asstringinitweb.param($ctx, "sku");
throw StockError{kind: "stock", message: "sold out", sku: $sku};
}
funclogError(err as Error) {
io.printf("onError: %s: %s\n", $err.kind, $err.message);
}
def app asweb.App initweb.new();
$app = web.get($app, "/buy/:sku", buy);
$app = web.onError($app, logError);
def srv ashttpd.Server inithttpd.listen("127.0.0.1:18405");
def server astaskofnullinitspawn {
web.serveOn($app, $srv);
returnnull;
};
def resp ashttp.Response inithttp.get("http://127.0.0.1:18405/buy/T-42", {});
time.sleep(time.fromMilliseconds(100)); # the hook runs after the 500 is sentio.printf("status %d\n", $resp.status);
httpd.shutdown($srv);
task.wait($server);