com.xyxy.platform.examples.showcase.demos.hystrix.web.HystrixExceptionHandler.java Source code

Java tutorial

Introduction

Here is the source code for com.xyxy.platform.examples.showcase.demos.hystrix.web.HystrixExceptionHandler.java

Source

/*******************************************************************************
 * Copyright (c) 2005, 2014
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.xyxy.platform.examples.showcase.demos.hystrix.web;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import com.xyxy.platform.modules.core.utils.Exceptions;
import com.xyxy.platform.modules.core.web.MediaTypes;

import com.netflix.hystrix.exception.HystrixBadRequestException;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import com.netflix.hystrix.exception.HystrixRuntimeException.FailureType;

/**
 * ExceptionHandler?Hystrix.
 * 
 *
 */
@ControllerAdvice
public class HystrixExceptionHandler extends ResponseEntityExceptionHandler {

    /**
     * ?Hystrix Runtime, :
     * Command(500).
     * Hystrix??(503).
     */
    @ExceptionHandler(value = { HystrixRuntimeException.class })
    public final ResponseEntity<?> handleException(HystrixRuntimeException e, WebRequest request) {
        HttpStatus status = HttpStatus.SERVICE_UNAVAILABLE;
        String message = e.getMessage();

        FailureType type = e.getFailureType();

        // ?
        if (type.equals(FailureType.COMMAND_EXCEPTION)) {
            status = HttpStatus.INTERNAL_SERVER_ERROR;
            message = Exceptions.getErrorMessageWithNestedException(e);
        }

        logger.error(message, e);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(MediaTypes.TEXT_PLAIN_UTF_8));
        return handleExceptionInternal(e, message, headers, status, request);
    }

    /**
     * ?Hystrix ClientException(404).
     * ClientException?, ?
     */
    @ExceptionHandler(value = { HystrixBadRequestException.class })
    public final ResponseEntity<?> handleException(HystrixBadRequestException e, WebRequest request) {
        String message = Exceptions.getErrorMessageWithNestedException(e);
        logger.error(message, e);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(MediaTypes.TEXT_PLAIN_UTF_8));
        return handleExceptionInternal(e, message, headers, HttpStatus.BAD_REQUEST, request);
    }
}