0
votes

This akka http route returns the file as expected. However, if the file does not exists, it returns a 500 Internal Error. How to return a 403 File Not Found error if the file does not exists?

 pathSingleSlash {
    get {
      complete(HttpEntity.fromFile(ContentTypes.`text/html(UTF-8)`, new java.io.File("example.html")))
    }
  }
2

2 Answers

1
votes

As @Allen Han said, you can wrapp it in a Try and use rejectEmptyResponse

  pathSingleSlash {
     get {
         rejectEmptyResponse {    
            complete(Try(HttpEntity.fromFile(ContentTypes.`text/html(UTF-8)`, new java.io.File("example.html")).toOption)
         }
     }
  }
0
votes

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.