001/* 002 * Copyright 2002-2012 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.scheduling.support; 018 019import java.lang.reflect.UndeclaredThrowableException; 020 021import org.springframework.util.Assert; 022import org.springframework.util.ErrorHandler; 023 024/** 025 * Runnable wrapper that catches any exception or error thrown from its 026 * delegate Runnable and allows an {@link ErrorHandler} to handle it. 027 * 028 * @author Juergen Hoeller 029 * @author Mark Fisher 030 * @since 3.0 031 */ 032public class DelegatingErrorHandlingRunnable implements Runnable { 033 034 private final Runnable delegate; 035 036 private final ErrorHandler errorHandler; 037 038 039 /** 040 * Create a new DelegatingErrorHandlingRunnable. 041 * @param delegate the Runnable implementation to delegate to 042 * @param errorHandler the ErrorHandler for handling any exceptions 043 */ 044 public DelegatingErrorHandlingRunnable(Runnable delegate, ErrorHandler errorHandler) { 045 Assert.notNull(delegate, "Delegate must not be null"); 046 Assert.notNull(errorHandler, "ErrorHandler must not be null"); 047 this.delegate = delegate; 048 this.errorHandler = errorHandler; 049 } 050 051 @Override 052 public void run() { 053 try { 054 this.delegate.run(); 055 } 056 catch (UndeclaredThrowableException ex) { 057 this.errorHandler.handleError(ex.getUndeclaredThrowable()); 058 } 059 catch (Throwable ex) { 060 this.errorHandler.handleError(ex); 061 } 062 } 063 064 @Override 065 public String toString() { 066 return "DelegatingErrorHandlingRunnable for " + this.delegate; 067 } 068 069}