All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.jk.services.server.JKServiceExceptionHandler Maven / Gradle / Ivy

Go to download

A set wrappers, filters, and API's that enables faster development in microservices in Java

The newest version!
/*
 * Copyright 2002-2023 Dr. Jalal Kiswani. 
 * Email: [email protected]
 * Check out https://j-framework.com for more details
 * 
 * All the opensource projects of Dr. Jalal Kiswani are free for personal and academic use only, 
 * for commercial usage and support, please contact the author.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jk.services.server;

import com.jk.core.context.JKContextFactory;
import com.jk.core.http.JKHttpStatus;
import com.jk.core.logging.JKLogger;
import com.jk.core.logging.JKLoggerFactory;
import com.jk.web.monitoring.JKMonitorService;
import com.mongodb.MongoException;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;

/**
 * This class implements the {@link ExceptionMapper} interface for handling
 * exceptions thrown within the JAX-RS application.
 * 
 * @author Dr. Jalal H. Kiswani
 * @version 1.0
 */
@Provider
public class JKServiceExceptionHandler implements ExceptionMapper {

	/**
	 * Represents the class logger.
	 */
	JKLogger logger = JKLoggerFactory.getLogger(getClass());

	/**
	 * Represents the HTTP request associated with the exception.
	 */
	@Context
	HttpServletRequest httpRequest;

	/**
	 * {@inheritDoc}
	 */
	public Response toResponse(Exception ex) {
		logger.error("Micorsrvice returned error to client. Context Info({}), with exception ({})) ",
				JKContextFactory.getCurrentContext().toString(), ex);
		Response response = null;
		if (ex instanceof WebApplicationException) {
			WebApplicationException e = (WebApplicationException) ex;
			response = e.getResponse();
		} else if (ex instanceof MongoException) {
			int status = JKHttpStatus.INTERNAL_SERVER_ERROR.value();
			response = Response.status(status).entity("Database Error, please check with the admin").type("text/plain")
					.build();
		} else {
			int status = JKHttpStatus.INTERNAL_SERVER_ERROR.value();
			response = Response.status(status).entity(ex.getMessage()).type("text/plain").build();
		}
		JKMonitorService.getInstance().publish(httpRequest, ex);
		return response;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy