Commit 36dd92e3 by Patryk Czarnik

Response i ExceptionMapper

parent f39b5379
package sklep.rest;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Response;
import sklep.db.DBConnection;
import sklep.db.DBException;
import sklep.db.ProductDAO;
......@@ -27,13 +28,25 @@ public class RProductsHtml {
}
}
// W tej metodzie pokazuję, jak wyglądaloby zwracanie różnych kodów odpowiedzi w zależności od sytuacji.
// Używamy klasy Response
@GET
@Path("/{id}")
public String oneProduct(@PathParam("id") int productId) throws DBException, RecordNotFound {
public Response oneProduct(@PathParam("id") int productId) {
try(DBConnection db = DBConnection.open()) {
ProductDAO productDAO = db.productDAO();
Product product = productDAO.findById(productId);
return "<!DOCTYPE html>\n<html><body>" + product.toHtml() + "</body></html>";
return Response.ok()
.entity("<!DOCTYPE html>\n<html><body>" + product.toHtml() + "</body></html>")
.build();
} catch (DBException e) {
return Response.serverError()
.entity("<!DOCTYPE html>\n<html><body><p>WIELKA BIEDA</p></body></html>")
.build();
} catch (RecordNotFound e) {
return Response.status(404)
.entity("<!DOCTYPE html>\n<html><body><p>BRAK TAKIEGO PRODUKTU</p></body></html>")
.build();
}
}
}
package sklep.rest.ext;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;
import sklep.db.RecordNotFound;
// Gdy taka klasa jest obecna w projekcie, to w każdej sytuacji, gdy metoda "restowa" kończy się wyjątkiem
// RecordNotFound, serwer odeśle odpowiedź przygotowaną przez tego mappera.
@Provider
public class RecordNotFoundMapper implements ExceptionMapper<RecordNotFound> {
@Override
public Response toResponse(RecordNotFound exception) {
String html = """
<html><body>
<h1>Nie znaleziono</h1>
<p style='color:red'>
""" + exception.getMessage()
+ "</p></body></html>";
return Response.status(404)
.type("text/html")
.entity(html)
.build();
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment