2013-04-03 13 views
5
import org.springframework.beans.TypeMismatchException; 
import javax.annotation.*; 
import javax.servlet.http.*; 
import org.springframework.http.HttpStatus; 
import org.springframework.stereotype.Controller; 
import org.springframework.context.annotation.Scope; 
import org.springframework.web.bind.annotation.*; 

@Controller 
@RequestMapping(value = "/aa") 
public class BaseController { 

    @RequestMapping(value = "/bb/{number}", method = RequestMethod.GET, produces = "plain/text") 
    public void test(@PathVariable final double number, final HttpServletResponse response) throws IOException { 
     throw new MyException("whatever"); 
    } 

    @ResponseBody 
    @ExceptionHandler(MyException.class) 
    public MyError handleMyException(final MyException exception, final HttpServletResponse response) throws IOException { 
     ... 
    } 

    @ResponseBody 
    @ExceptionHandler(TypeMismatchException.class) 
    public MyError handleTypeMismatchException(final TypeMismatchException exception, final HttpServletResponse response) throws IOException { 
     ... 
    } 

    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) 
    @ResponseBody 
    @ExceptionHandler 
    public MyError handleException(final Exception exception) throws IOException { 
     ... 
    } 
} 

Se chiamo http://example.com/aa/bb/20 la funzione handleMyException viene eseguita, come previsto.ExceptionHandler nella primavera

Tuttavia, se chiamo http://example.com/aa/bb/QQQ Mi aspetterei che la funzione viene chiamata handleTypeMismatchException, ma invece, HandleException è chiamato, con l'eccezione di tipo TypeMismatchException.

una soluzione sgradevole per rendere sarebbe sarebbe per verificare il tipo di eccezione all'interno handleException(), e chiamare handleTypeMismatchException se l'eccezione è di tipo TypeMismatchException.

ma perché ora funziona? il gestore di eccezioni viene scelto in fase di runtime in base al tipo di eccezione? o è scelto al momento della compilazione?

+0

Qual è l'eccezione generata nel caso di 'http: // example.com/aa/bb/QQQ' –

+0

la funzione handleException (eccezione eccezione finale) viene chiamata con un'eccezione di TypeMismatchException. –

risposta

3

Estratto official spring documentation:

Si utilizza il metodo @ExceptionHandler nota di un controller per specificare il metodo viene invocato quando viene generata un'eccezione di uno specifico tipo durante l'esecuzione di metodi regolatore

L'eccezione che si sta tentando di rilevare è generata dalla molla stessa (conversione da stringa a doppia), prima dell'esecuzione effettiva del metodo. La cattura non è nelle specifiche di @ExceptionHandler. Questo ha senso - in genere non vorresti rilevare le eccezioni generate dal framework stesso.

Problemi correlati