SpringBoot 默認400,500 異常處理,自定義異常處理


在resources 目錄下 創建 resources/error 即可,瀏覽器訪問會跳轉至定義的頁面中

 

 

ajax請求自定義異常處理 消息

UserNotExistException .java
package com.imooc.exception;
public class UserNotExistException extends RuntimeException {
	private static final long serialVersionUID = -6112780192479692859L;
	
	private String id;
	
	public UserNotExistException(String id) {
		super("user not exist");
		this.id = id;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

}

  ControllerExceptionHandler .java

package com.imooc.web.controller;

import java.util.HashMap;
import java.util.Map;

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 com.imooc.exception.UserNotExistException;

/**
 * 自定義異常處理響應內容
 */
@ControllerAdvice
public class ControllerExceptionHandler {
	// 拋出 UserNotExistException 異常都會被攔截
	@ExceptionHandler(UserNotExistException.class)
	@ResponseBody
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public Map<String, Object> handleUserNotExistException(UserNotExistException ex) {
		Map<String, Object> result = new HashMap<>();
		result.put("id", ex.getId());
		result.put("message", ex.getMessage());
		return result;
	}

}

  

業務邏輯中拋出異常

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM