I think you mean 404 Not Found. 403 is Forbidden.
Here is my solution:
pathSingleSlash {
get {
val file = new java.io.File("example.html")
val result = if (file.exists) HttpEntity.fromFile(ContentTypes.`text/html(UTF-8)`, file)
else HttpResponse(status = akka.http.scaladsl.model.StatusCodes.NotFound)
complete(result)
}
}
If you want to display some kind of JSON or message in the response, then for HttpResponse use HttpResponse(status = akka.http.scaladsl.model.StatusCodes.NotFound, entity = someMessage)
.
This isn't the way I would personally implement it, but without more testing, I cannot know if my alternate solution will work. So I would go with the solution I have described above.
Let me describe my alternate solution so you can try to implement it if you feel up to it. Usually, 500 status code means your code is throwing an uncaught exception, so instead of
val result = if (file.exists) HttpEntity.fromFile(ContentTypes.`text/html(UTF-8)`, new java.io.File("example.html"))
else HttpResponse(status = akka.http.scaladsl.model.StatusCodes.NotFound)
I would wrap result
in a Try monad or a try-catch block to handle the exception when it is thrown.
However, without further testing, I cannot be sure if the cause of the 500 status code is due to an exception, so for my answer here, I am going to go with what I have described above.