FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
expresscpp/example/error_handler.cpp at master · expresscpp/expresscpp · GitHub
expresscpp
/
expresscpp
Public
Notifications
You must be signed in to change notification settings
Fork
15
Star
96
Code
Issues
5
Pull requests
2
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
expresscpp
/
example
/
error_handler.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
57 lines (44 loc) · 1.57 KB
Breadcrumbs
expresscpp
/
example
/
error_handler.cpp
Copy path
File metadata and controls
57 lines (44 loc) · 1.57 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#
include
"
expresscpp/console.hpp
"
#
include
"
expresscpp/expresscpp.hpp
"
using
namespace
expresscpp
;
int
main
() {
ExpressCpp app;
auto
ErrorMiddleware = [&](
auto
ec,
auto
/*
req
*/
,
auto
res,
auto
/*
next
*/
) {
std::cerr <<
"
Internal Error:
"
<< ec.
message
() << std::endl;
res->
SetStatus
(
500
);
res->
Send
(
"
Internal Error
"
);
};
app.
Error
(ErrorMiddleware);
struct
User
{
std::string name;
uint8_t
age;
};
std::vector<User> users{{
"
john
"
,
30
}, {
"
steve
"
,
40
}};
app.
Get
(
"
/users/:userId
"
, [&](
auto
req,
auto
res,
auto
/*
next
*/
) {
auto
params = req->
GetParams
();
if
((params.
find
(
"
userId
"
) != params.
end
())) {
auto
id = params.
at
(
"
userId
"
);
const
int
userId =
std::stoi
(id);
//
ops, possible the user does not exist -> exception
auto
user = users.
at
(userId);
res->
Json
(
fmt::format
(
"
{{
\"
name
\"
:
\"
{}
\"
,
\"
age
\"
:{}}}
"
, user.
name
, user.
age
));
}
else
{
res->
SetStatus
(
404
);
res->
Send
(
R"(
{"error":"user not found"}
)"
);
}
});
constexpr
uint16_t
port =
8081
;
app.
Listen
(port,
[=](
auto
ec) {
if
(ec) {
std::cerr <<
"
ERROR:
"
<< ec.
message
() << std::endl;
std::cerr <<
"
exiting...
"
<< std::endl;
exit
(
1
);
}
std::cout <<
fmt::format
(
R"(
you can try now (should work): "curl http://localhost:{}/users/0"
)"
, port)
<< std::endl;
std::cout <<
fmt::format
(
R"(
and (should fail): "curl http://localhost:{}/users/10"
)"
, port) << std::endl;
})
.
Run
();
return
0
;
}
Back
|
FazBrowse Home
|
New Git URL