1 /** 2 * Licensed to the Apache Software Foundation (ASF) under one 3 * or more contributor license agreements. See the NOTICE file 4 * distributed with this work for additional information 5 * regarding copyright ownership. The ASF licenses this file 6 * to you under the Apache License, Version 2.0 (the 7 * "License"); you may not use this file except in compliance 8 * with the License. You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 package org.apache.zookeeper.server.jersey.resources; 20 21 import javax.ws.rs.core.Context; 22 import javax.ws.rs.core.Response; 23 import javax.ws.rs.core.UriInfo; 24 import javax.ws.rs.ext.ExceptionMapper; 25 import javax.ws.rs.ext.Provider; 26 27 import org.apache.zookeeper.KeeperException; 28 import org.apache.zookeeper.server.jersey.jaxb.ZError; 29 30 31 /** 32 * Map KeeperException to HTTP status codes 33 */ 34 @Provider 35 public class KeeperExceptionMapper implements ExceptionMapper<KeeperException> { 36 private UriInfo ui; 37 KeeperExceptionMapper(@ontext UriInfo ui)38 public KeeperExceptionMapper(@Context UriInfo ui) { 39 this.ui = ui; 40 } 41 toResponse(KeeperException e)42 public Response toResponse(KeeperException e) { 43 Response.Status status; 44 String message; 45 46 String path = e.getPath(); 47 48 switch(e.code()) { 49 case AUTHFAILED: 50 status = Response.Status.UNAUTHORIZED; 51 message = path + " not authorized"; 52 break; 53 case BADARGUMENTS: 54 status = Response.Status.BAD_REQUEST; 55 message = path + " bad arguments"; 56 break; 57 case BADVERSION: 58 status = Response.Status.PRECONDITION_FAILED; 59 message = path + " bad version"; 60 break; 61 case INVALIDACL: 62 status = Response.Status.BAD_REQUEST; 63 message = path + " invalid acl"; 64 break; 65 case NODEEXISTS: 66 status = Response.Status.CONFLICT; 67 message = path + " already exists"; 68 break; 69 case NONODE: 70 status = Response.Status.NOT_FOUND; 71 message = path + " not found"; 72 break; 73 case NOTEMPTY: 74 status = Response.Status.CONFLICT; 75 message = path + " not empty"; 76 break; 77 default: 78 status = Response.Status.fromStatusCode(502); // bad gateway 79 message = "Error processing request for " + path 80 + " : " + e.getMessage(); 81 } 82 83 return Response.status(status).entity( 84 new ZError(ui.getRequestUri().toString(), message)).build(); 85 } 86 } 87