推荐直接使用@ResponseStatus注解,文章最后有示例!

NoHandlerFoundException异常处理方法返回ResponseEntity对象,并设置statusHttpStatus.NOT_FOUND即可:


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import com.yilabao.domain.ReturnVO;

/**
 * 全局异常处理
 * 
 * @author yilabao
 * @date 2021年1月23日
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 404异常处理<br>
     * 返回ResponseEntity,保留网络请求404状态码
     * 
     * @author yilabao
     * @date 2021年1月23日
     * @param e
     * @return ResponseEntity<ReturnVO<String>>
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public ResponseEntity<ReturnVO<String>> noHandleFoundException(NoHandlerFoundException e) {
        String message = e.getMessage();
        LOG.error(message, e);
        ReturnVO<String> errorBody = new ReturnVO<String>().error(message);
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorBody);
    }

    /**
     * Exception异常处理
     * 
     * @author yilabao
     * @date 2021年1月23日
     * @param e
     * @return ReturnVO<String>
     */
    @ExceptionHandler(Exception.class)
    public ReturnVO<String> handleException(Exception e) {
        String message = e.getMessage();
        LOG.error(message, e);
        return new ReturnVO<String>().error(message);
    }

}

还试了一种方式,继承ResponseEntityExceptionHandler类,重写handleNoHandlerFoundException和handleExceptionInternalCustom方法,自定义404响应信息。

如果用第2种方式,第1种方式里面就不能处理NoHandlerFoundException和Exception,否则优先执行第1种。

注意添加配置参数:

spring:
    mvc:
        throw-exception-if-no-handler-found: true
    resources:
        add-mappings: false

20220127

直接使用@ResponseStatus注解!

20220318

    @org.springframework.web.bind.annotation.ResponseStatus(org.springframework.http.HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public AjaxResult handlerNoFoundException(NoHandlerFoundException e) {
        LOG.error(e.getMessage(), e);
        AjaxResult errorBody = AjaxResult.error(HttpStatus.NOT_FOUND, "路径不存在,请检查路径是否正确");
        return errorBody;
    }

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐