DefaultExceptionHandler.java 1.5 KB
Newer Older
武汉红喜's avatar
武汉红喜 已提交
1 2 3
package org.hongxi.whatsmars.boot.sample.web.exception;

import lombok.extern.slf4j.Slf4j;
武汉红喜's avatar
web  
武汉红喜 已提交
4 5
import org.hongxi.whatsmars.common.result.Result;
import org.hongxi.whatsmars.common.result.ResultHelper;
武汉红喜's avatar
武汉红喜 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by shenhongxi on 2020/8/16.
 */
@Slf4j
@ControllerAdvice
public class DefaultExceptionHandler {

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
武汉红喜's avatar
web  
武汉红喜 已提交
25
    public Result handleLogicException(HttpServletRequest request, BusinessException e) {
武汉红喜's avatar
武汉红喜 已提交
26
        log.error("business exception handled, request:{}", request.getRequestURI(), e);
武汉红喜's avatar
web  
武汉红喜 已提交
27
        return ResultHelper.newResult(e.getCode(), e.getMsg());
武汉红喜's avatar
武汉红喜 已提交
28 29 30 31 32
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    @ResponseBody
武汉红喜's avatar
web  
武汉红喜 已提交
33
    public Result handleException(HttpServletRequest request, Exception e) throws Exception {
武汉红喜's avatar
武汉红喜 已提交
34 35 36 37
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }
        log.error("exception handled, request:{}", request.getRequestURI(), e);
武汉红喜's avatar
web  
武汉红喜 已提交
38
        return ResultHelper.newResult(500, e.getMessage());
武汉红喜's avatar
武汉红喜 已提交
39 40
    }
}