Hello, guys!
My api-oriented application has the following structure in routes
$app->group("/api/v1/auth", function() {
$this->get("/login", function($request, $response, $args) {
try {
$params = array_map("trim", $request->getParams());
$v = new AuthValidate($params);
if($v->fail()) {
throw new CustomException(error_create($v->errors()));
}
if($this->auth->attempt($params['email'], $params['password'])) {
return $response->withJSON([
"data" => "ok"
]);
}
} catch (CustomException $e) {
$error = error_exception($e->getMessage());
return $response->withJSON(["errors" => $error]);
} catch (\Exception $e) {
return $response->withJSON([
"errors" => error_exception("error")
]);
}
})->setName("user-auth");
$this->get("/logout", function($request, $response, $args) {
try {
if(Auth::getCookie()) {
Auth::destroy(Auth::getCookie());
return $response->withJSON([
"data" => "ok"
]);
}
} catch (CustomException $e) {
$error = error_exception($e->getMessage());
return $response->withJSON(["errors" => $error]);
} catch (\Exception $e) {
return $response->withJSON([
"errors" => error_exception("error")
]);
}
})->setName("user-auth");
});
I specially placed 2 routes to show - the block of try catch is repeated everywhere. How can I get around this?
I myself see 2 options - either to redefine the standard way to send errors to api slim (how can this be done?), Or somehow, through a function or through controllers, can make this block into a function
Or how i can redeclare protected function renderJsonErrorMessage(Exception $exception)