Seitenhistorie
...
Codeblock | ||||
---|---|---|---|---|
| ||||
@Inject protected Provider<CustomRestContext> context; // Dazu müssen noch drei weitere Klassen importiert werden: import javax.inject.Inject; import javax.inject.Provider; import org.nuclos.api.context.CustomRestContext; |
Behandlung von Exception und Custom Responses, jegliche Exceptions die in der Methode nicht mit einem try/catch-Block behandelt wird, wird vom Container-Service (Tomcat/Glassfish) als 500-Fehler gemeldet.
Um dieses Verhalten anzupassen ist es notwendig die Exceptions mittels try/catch zu behandeln und korrekte eigene Responses zu liefern, als Beispiel:
Codeblock | ||||
---|---|---|---|---|
| ||||
package example.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.nuclos.api.rule.CustomRestRule;
import org.nuclos.api.exception.BusinessException;
@Path("Test")
@Rule(name="HandleException", description="Demonstrates how to handle exception in CustomRest")
public class HandleException implements CustomRestRule {
@GET
@Path("response/{parameter}")
@Produces("application/json")
public Response parameterTest(@PathParam("parameter") String parameter) {
try {
if( this.functionToThrowException(parameter) ) {
return Response.status(Response.Status.FORBIDDEN).entity(new Message("Dieser User hat keine Berechtigung für das Ausführen der Regel.")).build();
}
} catch (BusinessException e) {
// may also log error
return Response.status(Response.Status.BAD_REQUEST).entity(new Message(e.getMessage())).build();
}
return Response.status(Response.Status.NO_CONTENT).build();
}
private boolean functionToThrowException(String parameter) throws BusinessException {
if (parameter == null) {
throw BusinessException("No parameter given");
}
return "failure".equals(parameter);
}
// Any DTO class for response, will be JSON converted
public static class Message {
String message;
public Message(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
} |
Überblick
Inhalte