Spring全局異常處理

@Controller註解spa

@ControllerAdvice
public class ExceptionControllerAdvice implements Serializable{

    private final static Logger LOGGER = LoggerFactory.getLogger(ExceptionControllerAdvice.class);

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Result handleException(Exception ex){
        LOGGER.error(ex.getMessage(), ex);
        Result result = new Result();
        if(ex instanceof UnsatisfiedServletRequestParameterException) {
            result.setCode(ErrorCode.METHOD_NOT_FOUND.getCode());
            result.setMessage(ErrorCode.METHOD_NOT_FOUND.getMessage());
            return result;
        }
        if(ex instanceof CanalExecption){
            result.setCode(ErrorCode.SYSTEM_ERROR.getCode());
            result.setMessage(ex.getMessage());
        }else{
            result.setCode(ErrorCode.SYSTEM_ERROR.getCode());
            result.setMessage(ErrorCode.SYSTEM_ERROR.getMessage());
        }
        return result;
    }
}
相關文章
相關標籤/搜索